blob: 8794e37364a81ff794af71729ec914decc7a6401 [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 s = PyObject_Repr(v->ob_item[i]);
Victor Stinner5c733472013-11-18 21:11:57 +0100368 if (s == NULL)
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200369 goto error;
Victor Stinner5c733472013-11-18 21:11:57 +0100370
371 if (_PyUnicodeWriter_WriteStr(&writer, s) < 0) {
372 Py_DECREF(s);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200373 goto error;
Victor Stinner5c733472013-11-18 21:11:57 +0100374 }
375 Py_DECREF(s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 }
Victor Stinner5c733472013-11-18 21:11:57 +0100377
Victor Stinner4d3f1092013-11-19 12:09:00 +0100378 writer.overallocate = 0;
Victor Stinner5c733472013-11-18 21:11:57 +0100379 if (_PyUnicodeWriter_WriteChar(&writer, ']') < 0)
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200380 goto error;
Tim Petersa7259592001-06-16 05:11:17 +0000381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 Py_ReprLeave((PyObject *)v);
Victor Stinner5c733472013-11-18 21:11:57 +0100383 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200384
385error:
Victor Stinner5c733472013-11-18 21:11:57 +0100386 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200387 Py_ReprLeave((PyObject *)v);
388 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000389}
390
Martin v. Löwis18e16552006-02-15 17:27:45 +0000391static Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000392list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000393{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 return Py_SIZE(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000395}
396
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000397static int
Fred Drakea2f55112000-07-09 15:16:51 +0000398list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000399{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 Py_ssize_t i;
401 int cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i)
404 cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
405 Py_EQ);
406 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000407}
408
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000409static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000410list_item(PyListObject *a, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000411{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 if (i < 0 || i >= Py_SIZE(a)) {
413 if (indexerr == NULL) {
414 indexerr = PyUnicode_FromString(
415 "list index out of range");
416 if (indexerr == NULL)
417 return NULL;
418 }
419 PyErr_SetObject(PyExc_IndexError, indexerr);
420 return NULL;
421 }
422 Py_INCREF(a->ob_item[i]);
423 return a->ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000424}
425
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000426static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000427list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000428{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 PyListObject *np;
430 PyObject **src, **dest;
431 Py_ssize_t i, len;
432 if (ilow < 0)
433 ilow = 0;
434 else if (ilow > Py_SIZE(a))
435 ilow = Py_SIZE(a);
436 if (ihigh < ilow)
437 ihigh = ilow;
438 else if (ihigh > Py_SIZE(a))
439 ihigh = Py_SIZE(a);
440 len = ihigh - ilow;
441 np = (PyListObject *) PyList_New(len);
442 if (np == NULL)
443 return NULL;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 src = a->ob_item + ilow;
446 dest = np->ob_item;
447 for (i = 0; i < len; i++) {
448 PyObject *v = src[i];
449 Py_INCREF(v);
450 dest[i] = v;
451 }
452 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000453}
454
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000455PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000456PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000457{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 if (!PyList_Check(a)) {
459 PyErr_BadInternalCall();
460 return NULL;
461 }
462 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000463}
464
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000465static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000466list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000467{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 Py_ssize_t size;
469 Py_ssize_t i;
470 PyObject **src, **dest;
471 PyListObject *np;
472 if (!PyList_Check(bb)) {
473 PyErr_Format(PyExc_TypeError,
474 "can only concatenate list (not \"%.200s\") to list",
475 bb->ob_type->tp_name);
476 return NULL;
477 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000478#define b ((PyListObject *)bb)
Martin Panterb93d8632016-07-25 02:39:20 +0000479 if (Py_SIZE(a) > PY_SSIZE_T_MAX - Py_SIZE(b))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 return PyErr_NoMemory();
Martin Panterb93d8632016-07-25 02:39:20 +0000481 size = Py_SIZE(a) + Py_SIZE(b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 np = (PyListObject *) PyList_New(size);
483 if (np == NULL) {
484 return NULL;
485 }
486 src = a->ob_item;
487 dest = np->ob_item;
488 for (i = 0; i < Py_SIZE(a); i++) {
489 PyObject *v = src[i];
490 Py_INCREF(v);
491 dest[i] = v;
492 }
493 src = b->ob_item;
494 dest = np->ob_item + Py_SIZE(a);
495 for (i = 0; i < Py_SIZE(b); i++) {
496 PyObject *v = src[i];
497 Py_INCREF(v);
498 dest[i] = v;
499 }
500 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000501#undef b
502}
503
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000504static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000505list_repeat(PyListObject *a, Py_ssize_t n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000506{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 Py_ssize_t i, j;
508 Py_ssize_t size;
509 PyListObject *np;
510 PyObject **p, **items;
511 PyObject *elem;
512 if (n < 0)
513 n = 0;
Mark Dickinsonc0420fd2011-09-19 19:18:37 +0100514 if (n > 0 && Py_SIZE(a) > PY_SSIZE_T_MAX / n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 return PyErr_NoMemory();
Mark Dickinsonc0420fd2011-09-19 19:18:37 +0100516 size = Py_SIZE(a) * n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 if (size == 0)
518 return PyList_New(0);
519 np = (PyListObject *) PyList_New(size);
520 if (np == NULL)
521 return NULL;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 items = np->ob_item;
524 if (Py_SIZE(a) == 1) {
525 elem = a->ob_item[0];
526 for (i = 0; i < n; i++) {
527 items[i] = elem;
528 Py_INCREF(elem);
529 }
530 return (PyObject *) np;
531 }
532 p = np->ob_item;
533 items = a->ob_item;
534 for (i = 0; i < n; i++) {
535 for (j = 0; j < Py_SIZE(a); j++) {
536 *p = items[j];
537 Py_INCREF(*p);
538 p++;
539 }
540 }
541 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000542}
543
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000544static int
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200545_list_clear(PyListObject *a)
Armin Rigo93677f02004-07-29 12:40:23 +0000546{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 Py_ssize_t i;
548 PyObject **item = a->ob_item;
549 if (item != NULL) {
550 /* Because XDECREF can recursively invoke operations on
551 this list, we make it empty first. */
552 i = Py_SIZE(a);
553 Py_SIZE(a) = 0;
554 a->ob_item = NULL;
555 a->allocated = 0;
556 while (--i >= 0) {
557 Py_XDECREF(item[i]);
558 }
559 PyMem_FREE(item);
560 }
561 /* Never fails; the return value can be ignored.
562 Note that there is no guarantee that the list is actually empty
563 at this point, because XDECREF may have populated it again! */
564 return 0;
Armin Rigo93677f02004-07-29 12:40:23 +0000565}
566
Tim Peters8fc4a912004-07-31 21:53:19 +0000567/* a[ilow:ihigh] = v if v != NULL.
568 * del a[ilow:ihigh] if v == NULL.
569 *
570 * Special speed gimmick: when v is NULL and ihigh - ilow <= 8, it's
571 * guaranteed the call cannot fail.
572 */
Armin Rigo93677f02004-07-29 12:40:23 +0000573static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000574list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000575{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 /* Because [X]DECREF can recursively invoke list operations on
577 this list, we must postpone all [X]DECREF activity until
578 after the list is back in its canonical shape. Therefore
579 we must allocate an additional array, 'recycle', into which
580 we temporarily copy the items that are deleted from the
581 list. :-( */
582 PyObject *recycle_on_stack[8];
583 PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
584 PyObject **item;
585 PyObject **vitem = NULL;
586 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
587 Py_ssize_t n; /* # of elements in replacement list */
588 Py_ssize_t norig; /* # of elements in list getting replaced */
589 Py_ssize_t d; /* Change in size */
590 Py_ssize_t k;
591 size_t s;
592 int result = -1; /* guilty until proved innocent */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000593#define b ((PyListObject *)v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 if (v == NULL)
595 n = 0;
596 else {
597 if (a == b) {
598 /* Special case "a[i:j] = a" -- copy b first */
599 v = list_slice(b, 0, Py_SIZE(b));
600 if (v == NULL)
601 return result;
602 result = list_ass_slice(a, ilow, ihigh, v);
603 Py_DECREF(v);
604 return result;
605 }
606 v_as_SF = PySequence_Fast(v, "can only assign an iterable");
607 if(v_as_SF == NULL)
608 goto Error;
609 n = PySequence_Fast_GET_SIZE(v_as_SF);
610 vitem = PySequence_Fast_ITEMS(v_as_SF);
611 }
612 if (ilow < 0)
613 ilow = 0;
614 else if (ilow > Py_SIZE(a))
615 ilow = Py_SIZE(a);
Tim Peters8d9eb102004-07-31 02:24:20 +0000616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 if (ihigh < ilow)
618 ihigh = ilow;
619 else if (ihigh > Py_SIZE(a))
620 ihigh = Py_SIZE(a);
Armin Rigo93677f02004-07-29 12:40:23 +0000621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 norig = ihigh - ilow;
623 assert(norig >= 0);
624 d = n - norig;
625 if (Py_SIZE(a) + d == 0) {
626 Py_XDECREF(v_as_SF);
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200627 return _list_clear(a);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 }
629 item = a->ob_item;
630 /* recycle the items that we are about to remove */
631 s = norig * sizeof(PyObject *);
Benjamin Peterson5a7d9232016-09-06 17:58:25 -0700632 /* If norig == 0, item might be NULL, in which case we may not memcpy from it. */
633 if (s) {
634 if (s > sizeof(recycle_on_stack)) {
635 recycle = (PyObject **)PyMem_MALLOC(s);
636 if (recycle == NULL) {
637 PyErr_NoMemory();
638 goto Error;
639 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 }
Benjamin Peterson5a7d9232016-09-06 17:58:25 -0700641 memcpy(recycle, &item[ilow], s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 }
Tim Peters8d9eb102004-07-31 02:24:20 +0000643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 if (d < 0) { /* Delete -d items */
Victor Stinner2c40f642013-07-19 23:06:21 +0200645 Py_ssize_t tail;
646 tail = (Py_SIZE(a) - ihigh) * sizeof(PyObject *);
647 memmove(&item[ihigh+d], &item[ihigh], tail);
648 if (list_resize(a, Py_SIZE(a) + d) < 0) {
649 memmove(&item[ihigh], &item[ihigh+d], tail);
650 memcpy(&item[ilow], recycle, s);
651 goto Error;
652 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 item = a->ob_item;
654 }
655 else if (d > 0) { /* Insert d items */
656 k = Py_SIZE(a);
657 if (list_resize(a, k+d) < 0)
658 goto Error;
659 item = a->ob_item;
660 memmove(&item[ihigh+d], &item[ihigh],
661 (k - ihigh)*sizeof(PyObject *));
662 }
663 for (k = 0; k < n; k++, ilow++) {
664 PyObject *w = vitem[k];
665 Py_XINCREF(w);
666 item[ilow] = w;
667 }
668 for (k = norig - 1; k >= 0; --k)
669 Py_XDECREF(recycle[k]);
670 result = 0;
Tim Peters8d9eb102004-07-31 02:24:20 +0000671 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 if (recycle != recycle_on_stack)
673 PyMem_FREE(recycle);
674 Py_XDECREF(v_as_SF);
675 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000676#undef b
677}
678
Guido van Rossum234f9421993-06-17 12:35:49 +0000679int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000680PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000681{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 if (!PyList_Check(a)) {
683 PyErr_BadInternalCall();
684 return -1;
685 }
686 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000687}
688
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000689static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000690list_inplace_repeat(PyListObject *self, Py_ssize_t n)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000691{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 PyObject **items;
693 Py_ssize_t size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000694
695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 size = PyList_GET_SIZE(self);
697 if (size == 0 || n == 1) {
698 Py_INCREF(self);
699 return (PyObject *)self;
700 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 if (n < 1) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200703 (void)_list_clear(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 Py_INCREF(self);
705 return (PyObject *)self;
706 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 if (size > PY_SSIZE_T_MAX / n) {
709 return PyErr_NoMemory();
710 }
Christian Heimesaf98da12008-01-27 15:18:18 +0000711
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800712 if (list_resize(self, size*n) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 return NULL;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 p = size;
716 items = self->ob_item;
717 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
718 for (j = 0; j < size; j++) {
719 PyObject *o = items[j];
720 Py_INCREF(o);
721 items[p++] = o;
722 }
723 }
724 Py_INCREF(self);
725 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000726}
727
Guido van Rossum4a450d01991-04-03 19:05:18 +0000728static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000729list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000730{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 if (i < 0 || i >= Py_SIZE(a)) {
732 PyErr_SetString(PyExc_IndexError,
733 "list assignment index out of range");
734 return -1;
735 }
736 if (v == NULL)
737 return list_ass_slice(a, i, i+1, v);
738 Py_INCREF(v);
Serhiy Storchakaf01e4082016-04-10 18:12:01 +0300739 Py_SETREF(a->ob_item[i], v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 return 0;
Guido van Rossum4a450d01991-04-03 19:05:18 +0000741}
742
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200743/*[clinic input]
744list.insert
745
746 index: Py_ssize_t
747 object: object
748 /
749
750Insert object before index.
751[clinic start generated code]*/
752
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000753static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200754list_insert_impl(PyListObject *self, Py_ssize_t index, PyObject *object)
755/*[clinic end generated code: output=7f35e32f60c8cb78 input=858514cf894c7eab]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000756{
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200757 if (ins1(self, index, object) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 Py_RETURN_NONE;
759 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000760}
761
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200762/*[clinic input]
763list.clear
764
765Remove all items from list.
766[clinic start generated code]*/
767
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000768static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200769list_clear_impl(PyListObject *self)
770/*[clinic end generated code: output=67a1896c01f74362 input=ca3c1646856742f6]*/
Eli Benderskycbbaa962011-02-25 05:47:53 +0000771{
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200772 _list_clear(self);
Eli Benderskycbbaa962011-02-25 05:47:53 +0000773 Py_RETURN_NONE;
774}
775
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200776/*[clinic input]
777list.copy
778
779Return a shallow copy of the list.
780[clinic start generated code]*/
781
Eli Benderskycbbaa962011-02-25 05:47:53 +0000782static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200783list_copy_impl(PyListObject *self)
784/*[clinic end generated code: output=ec6b72d6209d418e input=6453ab159e84771f]*/
Eli Benderskycbbaa962011-02-25 05:47:53 +0000785{
786 return list_slice(self, 0, Py_SIZE(self));
787}
788
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200789/*[clinic input]
790list.append
791
792 object: object
793 /
794
795Append object to the end of the list.
796[clinic start generated code]*/
797
Eli Benderskycbbaa962011-02-25 05:47:53 +0000798static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200799list_append(PyListObject *self, PyObject *object)
800/*[clinic end generated code: output=7c096003a29c0eae input=43a3fe48a7066e91]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000801{
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200802 if (app1(self, object) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 Py_RETURN_NONE;
804 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000805}
806
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200807/*[clinic input]
808list.extend
809
810 iterable: object
811 /
812
813Extend list by appending elements from the iterable.
814[clinic start generated code]*/
815
Barry Warsawdedf6d61998-10-09 16:37:25 +0000816static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200817list_extend(PyListObject *self, PyObject *iterable)
818/*[clinic end generated code: output=630fb3bca0c8e789 input=9ec5ba3a81be3a4d]*/
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000819{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 PyObject *it; /* iter(v) */
821 Py_ssize_t m; /* size of self */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200822 Py_ssize_t n; /* guess for size of iterable */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 Py_ssize_t mn; /* m + n */
824 Py_ssize_t i;
825 PyObject *(*iternext)(PyObject *);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 /* Special cases:
828 1) lists and tuples which can use PySequence_Fast ops
829 2) extending self to self requires making a copy first
830 */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200831 if (PyList_CheckExact(iterable) || PyTuple_CheckExact(iterable) ||
832 (PyObject *)self == iterable) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 PyObject **src, **dest;
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200834 iterable = PySequence_Fast(iterable, "argument must be iterable");
835 if (!iterable)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 return NULL;
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200837 n = PySequence_Fast_GET_SIZE(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 if (n == 0) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200839 /* short circuit when iterable is empty */
840 Py_DECREF(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 Py_RETURN_NONE;
842 }
843 m = Py_SIZE(self);
Martin Panter94b39ce2017-01-14 06:30:37 +0000844 /* It should not be possible to allocate a list large enough to cause
845 an overflow on any relevant platform */
846 assert(m < PY_SSIZE_T_MAX - n);
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800847 if (list_resize(self, m + n) < 0) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200848 Py_DECREF(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 return NULL;
850 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200851 /* note that we may still have self == iterable here for the
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 * situation a.extend(a), but the following code works
853 * in that case too. Just make sure to resize self
854 * before calling PySequence_Fast_ITEMS.
855 */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200856 /* populate the end of self with iterable's items */
857 src = PySequence_Fast_ITEMS(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 dest = self->ob_item + m;
859 for (i = 0; i < n; i++) {
860 PyObject *o = src[i];
861 Py_INCREF(o);
862 dest[i] = o;
863 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200864 Py_DECREF(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 Py_RETURN_NONE;
866 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000867
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200868 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 if (it == NULL)
870 return NULL;
871 iternext = *it->ob_type->tp_iternext;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 /* Guess a result list size. */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200874 n = PyObject_LengthHint(iterable, 8);
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800875 if (n < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 Py_DECREF(it);
877 return NULL;
878 }
879 m = Py_SIZE(self);
Martin Panterb93d8632016-07-25 02:39:20 +0000880 if (m > PY_SSIZE_T_MAX - n) {
881 /* m + n overflowed; on the chance that n lied, and there really
882 * is enough room, ignore it. If n was telling the truth, we'll
883 * eventually run out of memory during the loop.
884 */
885 }
886 else {
887 mn = m + n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 /* Make room. */
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800889 if (list_resize(self, mn) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 goto error;
891 /* Make the list sane again. */
892 Py_SIZE(self) = m;
893 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 /* Run iterator to exhaustion. */
896 for (;;) {
897 PyObject *item = iternext(it);
898 if (item == NULL) {
899 if (PyErr_Occurred()) {
900 if (PyErr_ExceptionMatches(PyExc_StopIteration))
901 PyErr_Clear();
902 else
903 goto error;
904 }
905 break;
906 }
907 if (Py_SIZE(self) < self->allocated) {
908 /* steals ref */
909 PyList_SET_ITEM(self, Py_SIZE(self), item);
910 ++Py_SIZE(self);
911 }
912 else {
913 int status = app1(self, item);
914 Py_DECREF(item); /* append creates a new ref */
915 if (status < 0)
916 goto error;
917 }
918 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 /* Cut back result list if initial guess was too large. */
Victor Stinner32fd6ea2013-07-16 21:45:58 +0200921 if (Py_SIZE(self) < self->allocated) {
922 if (list_resize(self, Py_SIZE(self)) < 0)
923 goto error;
924 }
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 Py_DECREF(it);
927 Py_RETURN_NONE;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000928
929 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 Py_DECREF(it);
931 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000932}
933
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000934PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200935_PyList_Extend(PyListObject *self, PyObject *iterable)
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000936{
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200937 return list_extend(self, iterable);
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000938}
939
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000940static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000941list_inplace_concat(PyListObject *self, PyObject *other)
942{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 PyObject *result;
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000944
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200945 result = list_extend(self, other);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 if (result == NULL)
947 return result;
948 Py_DECREF(result);
949 Py_INCREF(self);
950 return (PyObject *)self;
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000951}
952
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200953/*[clinic input]
954list.pop
955
956 index: Py_ssize_t = -1
957 /
958
959Remove and return item at index (default last).
960
961Raises IndexError if list is empty or index is out of range.
962[clinic start generated code]*/
963
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000964static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200965list_pop_impl(PyListObject *self, Py_ssize_t index)
966/*[clinic end generated code: output=6bd69dcb3f17eca8 input=b83675976f329e6f]*/
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000967{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 PyObject *v;
969 int status;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 if (Py_SIZE(self) == 0) {
972 /* Special-case most common failure cause */
973 PyErr_SetString(PyExc_IndexError, "pop from empty list");
974 return NULL;
975 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200976 if (index < 0)
977 index += Py_SIZE(self);
978 if (index < 0 || index >= Py_SIZE(self)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 PyErr_SetString(PyExc_IndexError, "pop index out of range");
980 return NULL;
981 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200982 v = self->ob_item[index];
983 if (index == Py_SIZE(self) - 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 status = list_resize(self, Py_SIZE(self) - 1);
Victor Stinnerb27cd3e2013-07-08 22:20:44 +0200985 if (status >= 0)
986 return v; /* and v now owns the reference the list had */
987 else
988 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 }
990 Py_INCREF(v);
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200991 status = list_ass_slice(self, index, index+1, (PyObject *)NULL);
Victor Stinner095d99f2013-07-17 21:58:01 +0200992 if (status < 0) {
993 Py_DECREF(v);
994 return NULL;
995 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 return v;
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000997}
998
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000999/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
1000static void
1001reverse_slice(PyObject **lo, PyObject **hi)
1002{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 assert(lo && hi);
Tim Peters8e2e7ca2002-07-19 02:33:08 +00001004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 --hi;
1006 while (lo < hi) {
1007 PyObject *t = *lo;
1008 *lo = *hi;
1009 *hi = t;
1010 ++lo;
1011 --hi;
1012 }
Tim Peters8e2e7ca2002-07-19 02:33:08 +00001013}
1014
Tim Petersa64dc242002-08-01 02:13:36 +00001015/* Lots of code for an adaptive, stable, natural mergesort. There are many
1016 * pieces to this algorithm; read listsort.txt for overviews and details.
1017 */
Guido van Rossum3f236de1996-12-10 23:55:39 +00001018
Daniel Stutzbach98338222010-12-02 21:55:33 +00001019/* A sortslice contains a pointer to an array of keys and a pointer to
1020 * an array of corresponding values. In other words, keys[i]
1021 * corresponds with values[i]. If values == NULL, then the keys are
1022 * also the values.
1023 *
1024 * Several convenience routines are provided here, so that keys and
1025 * values are always moved in sync.
1026 */
1027
1028typedef struct {
1029 PyObject **keys;
1030 PyObject **values;
1031} sortslice;
1032
1033Py_LOCAL_INLINE(void)
1034sortslice_copy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j)
1035{
1036 s1->keys[i] = s2->keys[j];
1037 if (s1->values != NULL)
1038 s1->values[i] = s2->values[j];
1039}
1040
1041Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001042sortslice_copy_incr(sortslice *dst, sortslice *src)
1043{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001044 *dst->keys++ = *src->keys++;
1045 if (dst->values != NULL)
1046 *dst->values++ = *src->values++;
1047}
1048
1049Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001050sortslice_copy_decr(sortslice *dst, sortslice *src)
1051{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001052 *dst->keys-- = *src->keys--;
1053 if (dst->values != NULL)
1054 *dst->values-- = *src->values--;
1055}
1056
1057
1058Py_LOCAL_INLINE(void)
1059sortslice_memcpy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j,
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001060 Py_ssize_t n)
1061{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001062 memcpy(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
1063 if (s1->values != NULL)
1064 memcpy(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
1065}
1066
1067Py_LOCAL_INLINE(void)
1068sortslice_memmove(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j,
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001069 Py_ssize_t n)
1070{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001071 memmove(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
1072 if (s1->values != NULL)
1073 memmove(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
1074}
1075
1076Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001077sortslice_advance(sortslice *slice, Py_ssize_t n)
1078{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001079 slice->keys += n;
1080 if (slice->values != NULL)
1081 slice->values += n;
1082}
1083
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001084/* Comparison function: PyObject_RichCompareBool with Py_LT.
Tim Petersa64dc242002-08-01 02:13:36 +00001085 * Returns -1 on error, 1 if x < y, 0 if x >= y.
1086 */
Guido van Rossum3f236de1996-12-10 23:55:39 +00001087
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001088#define ISLT(X, Y) (PyObject_RichCompareBool(X, Y, Py_LT))
Tim Peters66860f62002-08-04 17:47:26 +00001089
1090/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +00001091 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
1092 started. It makes more sense in context <wink>. X and Y are PyObject*s.
1093*/
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001094#define IFLT(X, Y) if ((k = ISLT(X, Y)) < 0) goto fail; \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001096
1097/* binarysort is the best method for sorting small arrays: it does
1098 few compares, but can do data movement quadratic in the number of
1099 elements.
Guido van Rossum42812581998-06-17 14:15:44 +00001100 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +00001101 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001102 On entry, must have lo <= start <= hi, and that [lo, start) is already
1103 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +00001104 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001105 Even in case of error, the output slice will be some permutation of
1106 the input (nothing is lost or duplicated).
1107*/
Guido van Rossum3f236de1996-12-10 23:55:39 +00001108static int
Daniel Stutzbach98338222010-12-02 21:55:33 +00001109binarysort(sortslice lo, PyObject **hi, PyObject **start)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001110{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001111 Py_ssize_t k;
1112 PyObject **l, **p, **r;
1113 PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001114
Daniel Stutzbach98338222010-12-02 21:55:33 +00001115 assert(lo.keys <= start && start <= hi);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 /* assert [lo, start) is sorted */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001117 if (lo.keys == start)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 ++start;
1119 for (; start < hi; ++start) {
1120 /* set l to where *start belongs */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001121 l = lo.keys;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 r = start;
1123 pivot = *r;
1124 /* Invariants:
1125 * pivot >= all in [lo, l).
1126 * pivot < all in [r, start).
1127 * The second is vacuously true at the start.
1128 */
1129 assert(l < r);
1130 do {
1131 p = l + ((r - l) >> 1);
1132 IFLT(pivot, *p)
1133 r = p;
1134 else
1135 l = p+1;
1136 } while (l < r);
1137 assert(l == r);
1138 /* The invariants still hold, so pivot >= all in [lo, l) and
1139 pivot < all in [l, start), so pivot belongs at l. Note
1140 that if there are elements equal to pivot, l points to the
1141 first slot after them -- that's why this sort is stable.
1142 Slide over to make room.
1143 Caution: using memmove is much slower under MSVC 5;
1144 we're not usually moving many slots. */
1145 for (p = start; p > l; --p)
1146 *p = *(p-1);
1147 *l = pivot;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001148 if (lo.values != NULL) {
1149 Py_ssize_t offset = lo.values - lo.keys;
1150 p = start + offset;
1151 pivot = *p;
1152 l += offset;
1153 for (p = start + offset; p > l; --p)
1154 *p = *(p-1);
1155 *l = pivot;
1156 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 }
1158 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001159
1160 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001162}
1163
Tim Petersa64dc242002-08-01 02:13:36 +00001164/*
1165Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
1166is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001167
Tim Petersa64dc242002-08-01 02:13:36 +00001168 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001169
Tim Petersa64dc242002-08-01 02:13:36 +00001170or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001171
Tim Petersa64dc242002-08-01 02:13:36 +00001172 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +00001173
Tim Petersa64dc242002-08-01 02:13:36 +00001174Boolean *descending is set to 0 in the former case, or to 1 in the latter.
1175For its intended use in a stable mergesort, the strictness of the defn of
1176"descending" is needed so that the caller can safely reverse a descending
1177sequence without violating stability (strict > ensures there are no equal
1178elements to get out of order).
1179
1180Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001181*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001182static Py_ssize_t
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001183count_run(PyObject **lo, PyObject **hi, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 Py_ssize_t k;
1186 Py_ssize_t n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 assert(lo < hi);
1189 *descending = 0;
1190 ++lo;
1191 if (lo == hi)
1192 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 n = 2;
1195 IFLT(*lo, *(lo-1)) {
1196 *descending = 1;
1197 for (lo = lo+1; lo < hi; ++lo, ++n) {
1198 IFLT(*lo, *(lo-1))
1199 ;
1200 else
1201 break;
1202 }
1203 }
1204 else {
1205 for (lo = lo+1; lo < hi; ++lo, ++n) {
1206 IFLT(*lo, *(lo-1))
1207 break;
1208 }
1209 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 return n;
Tim Petersa64dc242002-08-01 02:13:36 +00001212fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001214}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001215
Tim Petersa64dc242002-08-01 02:13:36 +00001216/*
1217Locate the proper position of key in a sorted vector; if the vector contains
1218an element equal to key, return the position immediately to the left of
1219the leftmost equal element. [gallop_right() does the same except returns
1220the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001221
Tim Petersa64dc242002-08-01 02:13:36 +00001222"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001223
Tim Petersa64dc242002-08-01 02:13:36 +00001224"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1225hint is to the final result, the faster this runs.
1226
1227The return value is the int k in 0..n such that
1228
1229 a[k-1] < key <= a[k]
1230
1231pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1232key belongs at index k; or, IOW, the first k elements of a should precede
1233key, and the last n-k should follow key.
1234
1235Returns -1 on error. See listsort.txt for info on the method.
1236*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001237static Py_ssize_t
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001238gallop_left(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
Tim Petersa64dc242002-08-01 02:13:36 +00001239{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 Py_ssize_t ofs;
1241 Py_ssize_t lastofs;
1242 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 assert(key && a && n > 0 && hint >= 0 && hint < n);
Tim Petersa64dc242002-08-01 02:13:36 +00001245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001246 a += hint;
1247 lastofs = 0;
1248 ofs = 1;
1249 IFLT(*a, key) {
1250 /* a[hint] < key -- gallop right, until
1251 * a[hint + lastofs] < key <= a[hint + ofs]
1252 */
1253 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
1254 while (ofs < maxofs) {
1255 IFLT(a[ofs], key) {
1256 lastofs = ofs;
1257 ofs = (ofs << 1) + 1;
1258 if (ofs <= 0) /* int overflow */
1259 ofs = maxofs;
1260 }
1261 else /* key <= a[hint + ofs] */
1262 break;
1263 }
1264 if (ofs > maxofs)
1265 ofs = maxofs;
1266 /* Translate back to offsets relative to &a[0]. */
1267 lastofs += hint;
1268 ofs += hint;
1269 }
1270 else {
1271 /* key <= a[hint] -- gallop left, until
1272 * a[hint - ofs] < key <= a[hint - lastofs]
1273 */
1274 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
1275 while (ofs < maxofs) {
1276 IFLT(*(a-ofs), key)
1277 break;
1278 /* key <= a[hint - ofs] */
1279 lastofs = ofs;
1280 ofs = (ofs << 1) + 1;
1281 if (ofs <= 0) /* int overflow */
1282 ofs = maxofs;
1283 }
1284 if (ofs > maxofs)
1285 ofs = maxofs;
1286 /* Translate back to positive offsets relative to &a[0]. */
1287 k = lastofs;
1288 lastofs = hint - ofs;
1289 ofs = hint - k;
1290 }
1291 a -= hint;
Tim Petersa64dc242002-08-01 02:13:36 +00001292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1294 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1295 * right of lastofs but no farther right than ofs. Do a binary
1296 * search, with invariant a[lastofs-1] < key <= a[ofs].
1297 */
1298 ++lastofs;
1299 while (lastofs < ofs) {
1300 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 IFLT(a[m], key)
1303 lastofs = m+1; /* a[m] < key */
1304 else
1305 ofs = m; /* key <= a[m] */
1306 }
1307 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1308 return ofs;
Tim Petersa64dc242002-08-01 02:13:36 +00001309
1310fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001312}
1313
1314/*
1315Exactly like gallop_left(), except that if key already exists in a[0:n],
1316finds the position immediately to the right of the rightmost equal value.
1317
1318The return value is the int k in 0..n such that
1319
1320 a[k-1] <= key < a[k]
1321
1322or -1 if error.
1323
1324The code duplication is massive, but this is enough different given that
1325we're sticking to "<" comparisons that it's much harder to follow if
1326written as one routine with yet another "left or right?" flag.
1327*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001328static Py_ssize_t
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001329gallop_right(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
Tim Petersa64dc242002-08-01 02:13:36 +00001330{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 Py_ssize_t ofs;
1332 Py_ssize_t lastofs;
1333 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 assert(key && a && n > 0 && hint >= 0 && hint < n);
Tim Petersa64dc242002-08-01 02:13:36 +00001336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 a += hint;
1338 lastofs = 0;
1339 ofs = 1;
1340 IFLT(key, *a) {
1341 /* key < a[hint] -- gallop left, until
1342 * a[hint - ofs] <= key < a[hint - lastofs]
1343 */
1344 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
1345 while (ofs < maxofs) {
1346 IFLT(key, *(a-ofs)) {
1347 lastofs = ofs;
1348 ofs = (ofs << 1) + 1;
1349 if (ofs <= 0) /* int overflow */
1350 ofs = maxofs;
1351 }
1352 else /* a[hint - ofs] <= key */
1353 break;
1354 }
1355 if (ofs > maxofs)
1356 ofs = maxofs;
1357 /* Translate back to positive offsets relative to &a[0]. */
1358 k = lastofs;
1359 lastofs = hint - ofs;
1360 ofs = hint - k;
1361 }
1362 else {
1363 /* a[hint] <= key -- gallop right, until
1364 * a[hint + lastofs] <= key < a[hint + ofs]
1365 */
1366 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
1367 while (ofs < maxofs) {
1368 IFLT(key, a[ofs])
1369 break;
1370 /* a[hint + ofs] <= key */
1371 lastofs = ofs;
1372 ofs = (ofs << 1) + 1;
1373 if (ofs <= 0) /* int overflow */
1374 ofs = maxofs;
1375 }
1376 if (ofs > maxofs)
1377 ofs = maxofs;
1378 /* Translate back to offsets relative to &a[0]. */
1379 lastofs += hint;
1380 ofs += hint;
1381 }
1382 a -= hint;
Tim Petersa64dc242002-08-01 02:13:36 +00001383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1385 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1386 * right of lastofs but no farther right than ofs. Do a binary
1387 * search, with invariant a[lastofs-1] <= key < a[ofs].
1388 */
1389 ++lastofs;
1390 while (lastofs < ofs) {
1391 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 IFLT(key, a[m])
1394 ofs = m; /* key < a[m] */
1395 else
1396 lastofs = m+1; /* a[m] <= key */
1397 }
1398 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1399 return ofs;
Tim Petersa64dc242002-08-01 02:13:36 +00001400
1401fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001403}
1404
1405/* The maximum number of entries in a MergeState's pending-runs stack.
1406 * This is enough to sort arrays of size up to about
1407 * 32 * phi ** MAX_MERGE_PENDING
1408 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1409 * with 2**64 elements.
1410 */
1411#define MAX_MERGE_PENDING 85
1412
Tim Peterse05f65a2002-08-10 05:21:15 +00001413/* When we get into galloping mode, we stay there until both runs win less
1414 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
Tim Petersa64dc242002-08-01 02:13:36 +00001415 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001416#define MIN_GALLOP 7
Tim Petersa64dc242002-08-01 02:13:36 +00001417
1418/* Avoid malloc for small temp arrays. */
1419#define MERGESTATE_TEMP_SIZE 256
1420
1421/* One MergeState exists on the stack per invocation of mergesort. It's just
1422 * a convenient way to pass state around among the helper functions.
1423 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001424struct s_slice {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001425 sortslice base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 Py_ssize_t len;
Tim Peterse05f65a2002-08-10 05:21:15 +00001427};
1428
Tim Petersa64dc242002-08-01 02:13:36 +00001429typedef struct s_MergeState {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 /* This controls when we get *into* galloping mode. It's initialized
1431 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1432 * random data, and lower for highly structured data.
1433 */
1434 Py_ssize_t min_gallop;
Tim Peterse05f65a2002-08-10 05:21:15 +00001435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 /* 'a' is temp storage to help with merges. It contains room for
1437 * alloced entries.
1438 */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001439 sortslice a; /* may point to temparray below */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 Py_ssize_t alloced;
Tim Petersa64dc242002-08-01 02:13:36 +00001441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 /* A stack of n pending runs yet to be merged. Run #i starts at
1443 * address base[i] and extends for len[i] elements. It's always
1444 * true (so long as the indices are in bounds) that
1445 *
1446 * pending[i].base + pending[i].len == pending[i+1].base
1447 *
1448 * so we could cut the storage for this, but it's a minor amount,
1449 * and keeping all the info explicit simplifies the code.
1450 */
1451 int n;
1452 struct s_slice pending[MAX_MERGE_PENDING];
Tim Petersa64dc242002-08-01 02:13:36 +00001453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 /* 'a' points to this when possible, rather than muck with malloc. */
1455 PyObject *temparray[MERGESTATE_TEMP_SIZE];
Tim Petersa64dc242002-08-01 02:13:36 +00001456} MergeState;
1457
1458/* Conceptually a MergeState's constructor. */
1459static void
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001460merge_init(MergeState *ms, Py_ssize_t list_size, int has_keyfunc)
Tim Petersa64dc242002-08-01 02:13:36 +00001461{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 assert(ms != NULL);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001463 if (has_keyfunc) {
1464 /* The temporary space for merging will need at most half the list
1465 * size rounded up. Use the minimum possible space so we can use the
1466 * rest of temparray for other things. In particular, if there is
1467 * enough extra space, listsort() will use it to store the keys.
1468 */
1469 ms->alloced = (list_size + 1) / 2;
1470
1471 /* ms->alloced describes how many keys will be stored at
1472 ms->temparray, but we also need to store the values. Hence,
1473 ms->alloced is capped at half of MERGESTATE_TEMP_SIZE. */
1474 if (MERGESTATE_TEMP_SIZE / 2 < ms->alloced)
1475 ms->alloced = MERGESTATE_TEMP_SIZE / 2;
1476 ms->a.values = &ms->temparray[ms->alloced];
1477 }
1478 else {
1479 ms->alloced = MERGESTATE_TEMP_SIZE;
1480 ms->a.values = NULL;
1481 }
1482 ms->a.keys = ms->temparray;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 ms->n = 0;
1484 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001485}
1486
1487/* Free all the temp memory owned by the MergeState. This must be called
1488 * when you're done with a MergeState, and may be called before then if
1489 * you want to free the temp memory early.
1490 */
1491static void
1492merge_freemem(MergeState *ms)
1493{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 assert(ms != NULL);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001495 if (ms->a.keys != ms->temparray)
1496 PyMem_Free(ms->a.keys);
Tim Petersa64dc242002-08-01 02:13:36 +00001497}
1498
1499/* Ensure enough temp memory for 'need' array slots is available.
1500 * Returns 0 on success and -1 if the memory can't be gotten.
1501 */
1502static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001503merge_getmem(MergeState *ms, Py_ssize_t need)
Tim Petersa64dc242002-08-01 02:13:36 +00001504{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001505 int multiplier;
1506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 assert(ms != NULL);
1508 if (need <= ms->alloced)
1509 return 0;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001510
1511 multiplier = ms->a.values != NULL ? 2 : 1;
1512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 /* Don't realloc! That can cost cycles to copy the old data, but
1514 * we don't care what's in the block.
1515 */
1516 merge_freemem(ms);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001517 if ((size_t)need > PY_SSIZE_T_MAX / sizeof(PyObject*) / multiplier) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 PyErr_NoMemory();
1519 return -1;
1520 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001521 ms->a.keys = (PyObject**)PyMem_Malloc(multiplier * need
1522 * sizeof(PyObject *));
1523 if (ms->a.keys != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 ms->alloced = need;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001525 if (ms->a.values != NULL)
1526 ms->a.values = &ms->a.keys[need];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 return 0;
1528 }
1529 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001531}
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1533 merge_getmem(MS, NEED))
Tim Petersa64dc242002-08-01 02:13:36 +00001534
Daniel Stutzbach98338222010-12-02 21:55:33 +00001535/* Merge the na elements starting at ssa with the nb elements starting at
1536 * ssb.keys = ssa.keys + na in a stable way, in-place. na and nb must be > 0.
1537 * Must also have that ssa.keys[na-1] belongs at the end of the merge, and
1538 * should have na <= nb. See listsort.txt for more info. Return 0 if
1539 * successful, -1 if error.
Tim Petersa64dc242002-08-01 02:13:36 +00001540 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001541static Py_ssize_t
Daniel Stutzbach98338222010-12-02 21:55:33 +00001542merge_lo(MergeState *ms, sortslice ssa, Py_ssize_t na,
1543 sortslice ssb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001544{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 Py_ssize_t k;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001546 sortslice dest;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 int result = -1; /* guilty until proved innocent */
1548 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001549
Daniel Stutzbach98338222010-12-02 21:55:33 +00001550 assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
1551 assert(ssa.keys + na == ssb.keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001552 if (MERGE_GETMEM(ms, na) < 0)
1553 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001554 sortslice_memcpy(&ms->a, 0, &ssa, 0, na);
1555 dest = ssa;
1556 ssa = ms->a;
Tim Petersa64dc242002-08-01 02:13:36 +00001557
Daniel Stutzbach98338222010-12-02 21:55:33 +00001558 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 --nb;
1560 if (nb == 0)
1561 goto Succeed;
1562 if (na == 1)
1563 goto CopyB;
Tim Petersa64dc242002-08-01 02:13:36 +00001564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 min_gallop = ms->min_gallop;
1566 for (;;) {
1567 Py_ssize_t acount = 0; /* # of times A won in a row */
1568 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 /* Do the straightforward thing until (if ever) one run
1571 * appears to win consistently.
1572 */
1573 for (;;) {
1574 assert(na > 1 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001575 k = ISLT(ssb.keys[0], ssa.keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 if (k) {
1577 if (k < 0)
1578 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001579 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 ++bcount;
1581 acount = 0;
1582 --nb;
1583 if (nb == 0)
1584 goto Succeed;
1585 if (bcount >= min_gallop)
1586 break;
1587 }
1588 else {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001589 sortslice_copy_incr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 ++acount;
1591 bcount = 0;
1592 --na;
1593 if (na == 1)
1594 goto CopyB;
1595 if (acount >= min_gallop)
1596 break;
1597 }
1598 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 /* One run is winning so consistently that galloping may
1601 * be a huge win. So try that, and continue galloping until
1602 * (if ever) neither run appears to be winning consistently
1603 * anymore.
1604 */
1605 ++min_gallop;
1606 do {
1607 assert(na > 1 && nb > 0);
1608 min_gallop -= min_gallop > 1;
1609 ms->min_gallop = min_gallop;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001610 k = gallop_right(ssb.keys[0], ssa.keys, na, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 acount = k;
1612 if (k) {
1613 if (k < 0)
1614 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001615 sortslice_memcpy(&dest, 0, &ssa, 0, k);
1616 sortslice_advance(&dest, k);
1617 sortslice_advance(&ssa, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 na -= k;
1619 if (na == 1)
1620 goto CopyB;
1621 /* na==0 is impossible now if the comparison
1622 * function is consistent, but we can't assume
1623 * that it is.
1624 */
1625 if (na == 0)
1626 goto Succeed;
1627 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001628 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001629 --nb;
1630 if (nb == 0)
1631 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001632
Daniel Stutzbach98338222010-12-02 21:55:33 +00001633 k = gallop_left(ssa.keys[0], ssb.keys, nb, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 bcount = k;
1635 if (k) {
1636 if (k < 0)
1637 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001638 sortslice_memmove(&dest, 0, &ssb, 0, k);
1639 sortslice_advance(&dest, k);
1640 sortslice_advance(&ssb, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001641 nb -= k;
1642 if (nb == 0)
1643 goto Succeed;
1644 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001645 sortslice_copy_incr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 --na;
1647 if (na == 1)
1648 goto CopyB;
1649 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
1650 ++min_gallop; /* penalize it for leaving galloping mode */
1651 ms->min_gallop = min_gallop;
1652 }
Tim Petersa64dc242002-08-01 02:13:36 +00001653Succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 result = 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001655Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001656 if (na)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001657 sortslice_memcpy(&dest, 0, &ssa, 0, na);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 return result;
Tim Petersa64dc242002-08-01 02:13:36 +00001659CopyB:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 assert(na == 1 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001661 /* The last element of ssa belongs at the end of the merge. */
1662 sortslice_memmove(&dest, 0, &ssb, 0, nb);
1663 sortslice_copy(&dest, nb, &ssa, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001665}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001666
Daniel Stutzbach98338222010-12-02 21:55:33 +00001667/* Merge the na elements starting at pa with the nb elements starting at
1668 * ssb.keys = ssa.keys + na in a stable way, in-place. na and nb must be > 0.
1669 * Must also have that ssa.keys[na-1] belongs at the end of the merge, and
1670 * should have na >= nb. See listsort.txt for more info. Return 0 if
1671 * successful, -1 if error.
Tim Petersa64dc242002-08-01 02:13:36 +00001672 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001673static Py_ssize_t
Daniel Stutzbach98338222010-12-02 21:55:33 +00001674merge_hi(MergeState *ms, sortslice ssa, Py_ssize_t na,
1675 sortslice ssb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001676{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 Py_ssize_t k;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001678 sortslice dest, basea, baseb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 int result = -1; /* guilty until proved innocent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001681
Daniel Stutzbach98338222010-12-02 21:55:33 +00001682 assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
1683 assert(ssa.keys + na == ssb.keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 if (MERGE_GETMEM(ms, nb) < 0)
1685 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001686 dest = ssb;
1687 sortslice_advance(&dest, nb-1);
1688 sortslice_memcpy(&ms->a, 0, &ssb, 0, nb);
1689 basea = ssa;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 baseb = ms->a;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001691 ssb.keys = ms->a.keys + nb - 1;
1692 if (ssb.values != NULL)
1693 ssb.values = ms->a.values + nb - 1;
1694 sortslice_advance(&ssa, na - 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001695
Daniel Stutzbach98338222010-12-02 21:55:33 +00001696 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 --na;
1698 if (na == 0)
1699 goto Succeed;
1700 if (nb == 1)
1701 goto CopyA;
Tim Petersa64dc242002-08-01 02:13:36 +00001702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001703 min_gallop = ms->min_gallop;
1704 for (;;) {
1705 Py_ssize_t acount = 0; /* # of times A won in a row */
1706 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 /* Do the straightforward thing until (if ever) one run
1709 * appears to win consistently.
1710 */
1711 for (;;) {
1712 assert(na > 0 && nb > 1);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001713 k = ISLT(ssb.keys[0], ssa.keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 if (k) {
1715 if (k < 0)
1716 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001717 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 ++acount;
1719 bcount = 0;
1720 --na;
1721 if (na == 0)
1722 goto Succeed;
1723 if (acount >= min_gallop)
1724 break;
1725 }
1726 else {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001727 sortslice_copy_decr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 ++bcount;
1729 acount = 0;
1730 --nb;
1731 if (nb == 1)
1732 goto CopyA;
1733 if (bcount >= min_gallop)
1734 break;
1735 }
1736 }
Tim Petersa64dc242002-08-01 02:13:36 +00001737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 /* One run is winning so consistently that galloping may
1739 * be a huge win. So try that, and continue galloping until
1740 * (if ever) neither run appears to be winning consistently
1741 * anymore.
1742 */
1743 ++min_gallop;
1744 do {
1745 assert(na > 0 && nb > 1);
1746 min_gallop -= min_gallop > 1;
1747 ms->min_gallop = min_gallop;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001748 k = gallop_right(ssb.keys[0], basea.keys, na, na-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001749 if (k < 0)
1750 goto Fail;
1751 k = na - k;
1752 acount = k;
1753 if (k) {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001754 sortslice_advance(&dest, -k);
1755 sortslice_advance(&ssa, -k);
1756 sortslice_memmove(&dest, 1, &ssa, 1, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 na -= k;
1758 if (na == 0)
1759 goto Succeed;
1760 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001761 sortslice_copy_decr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 --nb;
1763 if (nb == 1)
1764 goto CopyA;
Tim Petersa64dc242002-08-01 02:13:36 +00001765
Daniel Stutzbach98338222010-12-02 21:55:33 +00001766 k = gallop_left(ssa.keys[0], baseb.keys, nb, nb-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 if (k < 0)
1768 goto Fail;
1769 k = nb - k;
1770 bcount = k;
1771 if (k) {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001772 sortslice_advance(&dest, -k);
1773 sortslice_advance(&ssb, -k);
1774 sortslice_memcpy(&dest, 1, &ssb, 1, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 nb -= k;
1776 if (nb == 1)
1777 goto CopyA;
1778 /* nb==0 is impossible now if the comparison
1779 * function is consistent, but we can't assume
1780 * that it is.
1781 */
1782 if (nb == 0)
1783 goto Succeed;
1784 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001785 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 --na;
1787 if (na == 0)
1788 goto Succeed;
1789 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
1790 ++min_gallop; /* penalize it for leaving galloping mode */
1791 ms->min_gallop = min_gallop;
1792 }
Tim Petersa64dc242002-08-01 02:13:36 +00001793Succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 result = 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001795Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 if (nb)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001797 sortslice_memcpy(&dest, -(nb-1), &baseb, 0, nb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 return result;
Tim Petersa64dc242002-08-01 02:13:36 +00001799CopyA:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 assert(nb == 1 && na > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001801 /* The first element of ssb belongs at the front of the merge. */
1802 sortslice_memmove(&dest, 1-na, &ssa, 1-na, na);
1803 sortslice_advance(&dest, -na);
1804 sortslice_advance(&ssa, -na);
1805 sortslice_copy(&dest, 0, &ssb, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001807}
1808
1809/* Merge the two runs at stack indices i and i+1.
1810 * Returns 0 on success, -1 on error.
1811 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001812static Py_ssize_t
1813merge_at(MergeState *ms, Py_ssize_t i)
Tim Petersa64dc242002-08-01 02:13:36 +00001814{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001815 sortslice ssa, ssb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 Py_ssize_t na, nb;
1817 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 assert(ms != NULL);
1820 assert(ms->n >= 2);
1821 assert(i >= 0);
1822 assert(i == ms->n - 2 || i == ms->n - 3);
Tim Petersa64dc242002-08-01 02:13:36 +00001823
Daniel Stutzbach98338222010-12-02 21:55:33 +00001824 ssa = ms->pending[i].base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001825 na = ms->pending[i].len;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001826 ssb = ms->pending[i+1].base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 nb = ms->pending[i+1].len;
1828 assert(na > 0 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001829 assert(ssa.keys + na == ssb.keys);
Tim Petersa64dc242002-08-01 02:13:36 +00001830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 /* Record the length of the combined runs; if i is the 3rd-last
1832 * run now, also slide over the last run (which isn't involved
1833 * in this merge). The current run i+1 goes away in any case.
1834 */
1835 ms->pending[i].len = na + nb;
1836 if (i == ms->n - 3)
1837 ms->pending[i+1] = ms->pending[i+2];
1838 --ms->n;
Tim Petersa64dc242002-08-01 02:13:36 +00001839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 /* Where does b start in a? Elements in a before that can be
1841 * ignored (already in place).
1842 */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001843 k = gallop_right(*ssb.keys, ssa.keys, na, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001844 if (k < 0)
1845 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001846 sortslice_advance(&ssa, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 na -= k;
1848 if (na == 0)
1849 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 /* Where does a end in b? Elements in b after that can be
1852 * ignored (already in place).
1853 */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001854 nb = gallop_left(ssa.keys[na-1], ssb.keys, nb, nb-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 if (nb <= 0)
1856 return nb;
Tim Petersa64dc242002-08-01 02:13:36 +00001857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 /* Merge what remains of the runs, using a temp array with
1859 * min(na, nb) elements.
1860 */
1861 if (na <= nb)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001862 return merge_lo(ms, ssa, na, ssb, nb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 else
Daniel Stutzbach98338222010-12-02 21:55:33 +00001864 return merge_hi(ms, ssa, na, ssb, nb);
Tim Petersa64dc242002-08-01 02:13:36 +00001865}
1866
1867/* Examine the stack of runs waiting to be merged, merging adjacent runs
1868 * until the stack invariants are re-established:
1869 *
1870 * 1. len[-3] > len[-2] + len[-1]
1871 * 2. len[-2] > len[-1]
1872 *
1873 * See listsort.txt for more info.
1874 *
1875 * Returns 0 on success, -1 on error.
1876 */
1877static int
1878merge_collapse(MergeState *ms)
1879{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 assert(ms);
1883 while (ms->n > 1) {
1884 Py_ssize_t n = ms->n - 2;
Benjamin Petersonb808d592015-02-25 10:12:26 -05001885 if ((n > 0 && p[n-1].len <= p[n].len + p[n+1].len) ||
1886 (n > 1 && p[n-2].len <= p[n-1].len + p[n].len)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 if (p[n-1].len < p[n+1].len)
1888 --n;
1889 if (merge_at(ms, n) < 0)
1890 return -1;
1891 }
1892 else if (p[n].len <= p[n+1].len) {
1893 if (merge_at(ms, n) < 0)
1894 return -1;
1895 }
1896 else
1897 break;
1898 }
1899 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001900}
1901
1902/* Regardless of invariants, merge all runs on the stack until only one
1903 * remains. This is used at the end of the mergesort.
1904 *
1905 * Returns 0 on success, -1 on error.
1906 */
1907static int
1908merge_force_collapse(MergeState *ms)
1909{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 assert(ms);
1913 while (ms->n > 1) {
1914 Py_ssize_t n = ms->n - 2;
1915 if (n > 0 && p[n-1].len < p[n+1].len)
1916 --n;
1917 if (merge_at(ms, n) < 0)
1918 return -1;
1919 }
1920 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001921}
1922
1923/* Compute a good value for the minimum run length; natural runs shorter
1924 * than this are boosted artificially via binary insertion.
1925 *
1926 * If n < 64, return n (it's too small to bother with fancy stuff).
1927 * Else if n is an exact power of 2, return 32.
1928 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1929 * strictly less than, an exact power of 2.
1930 *
1931 * See listsort.txt for more info.
1932 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001933static Py_ssize_t
1934merge_compute_minrun(Py_ssize_t n)
Tim Petersa64dc242002-08-01 02:13:36 +00001935{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */
Tim Petersa64dc242002-08-01 02:13:36 +00001937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001938 assert(n >= 0);
1939 while (n >= 64) {
1940 r |= n & 1;
1941 n >>= 1;
1942 }
1943 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001944}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001945
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001946static void
Daniel Stutzbach98338222010-12-02 21:55:33 +00001947reverse_sortslice(sortslice *s, Py_ssize_t n)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001948{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001949 reverse_slice(s->keys, &s->keys[n]);
1950 if (s->values != NULL)
1951 reverse_slice(s->values, &s->values[n]);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001952}
1953
Tim Petersa64dc242002-08-01 02:13:36 +00001954/* An adaptive, stable, natural mergesort. See listsort.txt.
1955 * Returns Py_None on success, NULL on error. Even in case of error, the
1956 * list will be some permutation of its input state (nothing is lost or
1957 * duplicated).
1958 */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02001959/*[clinic input]
1960list.sort
1961
1962 *
1963 key as keyfunc: object = None
Serhiy Storchaka202fda52017-03-12 10:10:47 +02001964 reverse: bool(accept={int}) = False
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02001965
1966Stable sort *IN PLACE*.
1967[clinic start generated code]*/
1968
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001969static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02001970list_sort_impl(PyListObject *self, PyObject *keyfunc, int reverse)
Serhiy Storchaka202fda52017-03-12 10:10:47 +02001971/*[clinic end generated code: output=57b9f9c5e23fbe42 input=b0fcf743982c5b90]*/
Guido van Rossum3f236de1996-12-10 23:55:39 +00001972{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 MergeState ms;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 Py_ssize_t nremaining;
1975 Py_ssize_t minrun;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001976 sortslice lo;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 Py_ssize_t saved_ob_size, saved_allocated;
1978 PyObject **saved_ob_item;
1979 PyObject **final_ob_item;
1980 PyObject *result = NULL; /* guilty until proved innocent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 Py_ssize_t i;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001982 PyObject **keys;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 assert(self != NULL);
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02001985 assert(PyList_Check(self));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 if (keyfunc == Py_None)
1987 keyfunc = NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 /* The list is temporarily made empty, so that mutations performed
1990 * by comparison functions can't affect the slice of memory we're
1991 * sorting (allowing mutations during sorting is a core-dump
1992 * factory, since ob_item may change).
1993 */
1994 saved_ob_size = Py_SIZE(self);
1995 saved_ob_item = self->ob_item;
1996 saved_allocated = self->allocated;
1997 Py_SIZE(self) = 0;
1998 self->ob_item = NULL;
1999 self->allocated = -1; /* any operation will reset it to >= 0 */
Tim Peters330f9e92002-07-19 07:05:44 +00002000
Daniel Stutzbach98338222010-12-02 21:55:33 +00002001 if (keyfunc == NULL) {
2002 keys = NULL;
2003 lo.keys = saved_ob_item;
2004 lo.values = NULL;
2005 }
2006 else {
2007 if (saved_ob_size < MERGESTATE_TEMP_SIZE/2)
2008 /* Leverage stack space we allocated but won't otherwise use */
2009 keys = &ms.temparray[saved_ob_size+1];
2010 else {
2011 keys = PyMem_MALLOC(sizeof(PyObject *) * saved_ob_size);
Benjamin Peterson0823ffb2015-04-23 17:04:36 -04002012 if (keys == NULL) {
2013 PyErr_NoMemory();
2014 goto keyfunc_fail;
2015 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00002017
2018 for (i = 0; i < saved_ob_size ; i++) {
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01002019 keys[i] = PyObject_CallFunctionObjArgs(keyfunc, saved_ob_item[i],
2020 NULL);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002021 if (keys[i] == NULL) {
2022 for (i=i-1 ; i>=0 ; i--)
2023 Py_DECREF(keys[i]);
Benjamin Peterson4a42cd42014-03-15 12:21:28 -05002024 if (saved_ob_size >= MERGESTATE_TEMP_SIZE/2)
Daniel Stutzbach8eda5f72011-03-02 23:37:50 +00002025 PyMem_FREE(keys);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002026 goto keyfunc_fail;
2027 }
2028 }
2029
2030 lo.keys = keys;
2031 lo.values = saved_ob_item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002032 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002033
Daniel Stutzbach98338222010-12-02 21:55:33 +00002034 merge_init(&ms, saved_ob_size, keys != NULL);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002036 nremaining = saved_ob_size;
2037 if (nremaining < 2)
2038 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00002039
Benjamin Peterson05380642010-08-23 19:35:39 +00002040 /* Reverse sort stability achieved by initially reversing the list,
2041 applying a stable forward sort, then reversing the final result. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00002042 if (reverse) {
2043 if (keys != NULL)
2044 reverse_slice(&keys[0], &keys[saved_ob_size]);
2045 reverse_slice(&saved_ob_item[0], &saved_ob_item[saved_ob_size]);
2046 }
Benjamin Peterson05380642010-08-23 19:35:39 +00002047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 /* March over the array once, left to right, finding natural runs,
2049 * and extending short natural runs to minrun elements.
2050 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 minrun = merge_compute_minrun(nremaining);
2052 do {
2053 int descending;
2054 Py_ssize_t n;
Tim Peters330f9e92002-07-19 07:05:44 +00002055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 /* Identify next run. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00002057 n = count_run(lo.keys, lo.keys + nremaining, &descending);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 if (n < 0)
2059 goto fail;
2060 if (descending)
Daniel Stutzbach98338222010-12-02 21:55:33 +00002061 reverse_sortslice(&lo, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 /* If short, extend to min(minrun, nremaining). */
2063 if (n < minrun) {
2064 const Py_ssize_t force = nremaining <= minrun ?
2065 nremaining : minrun;
Daniel Stutzbach98338222010-12-02 21:55:33 +00002066 if (binarysort(lo, lo.keys + force, lo.keys + n) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 goto fail;
2068 n = force;
2069 }
2070 /* Push run onto pending-runs stack, and maybe merge. */
2071 assert(ms.n < MAX_MERGE_PENDING);
2072 ms.pending[ms.n].base = lo;
2073 ms.pending[ms.n].len = n;
2074 ++ms.n;
2075 if (merge_collapse(&ms) < 0)
2076 goto fail;
2077 /* Advance to find next run. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00002078 sortslice_advance(&lo, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 nremaining -= n;
2080 } while (nremaining);
Tim Peters330f9e92002-07-19 07:05:44 +00002081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002082 if (merge_force_collapse(&ms) < 0)
2083 goto fail;
2084 assert(ms.n == 1);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002085 assert(keys == NULL
2086 ? ms.pending[0].base.keys == saved_ob_item
2087 : ms.pending[0].base.keys == &keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 assert(ms.pending[0].len == saved_ob_size);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002089 lo = ms.pending[0].base;
Tim Petersa64dc242002-08-01 02:13:36 +00002090
2091succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00002093fail:
Daniel Stutzbach98338222010-12-02 21:55:33 +00002094 if (keys != NULL) {
2095 for (i = 0; i < saved_ob_size; i++)
2096 Py_DECREF(keys[i]);
Benjamin Petersonef87f8c2014-03-14 21:54:31 -05002097 if (saved_ob_size >= MERGESTATE_TEMP_SIZE/2)
Daniel Stutzbach98338222010-12-02 21:55:33 +00002098 PyMem_FREE(keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 if (self->allocated != -1 && result != NULL) {
2102 /* The user mucked with the list during the sort,
2103 * and we don't already have another error to report.
2104 */
2105 PyErr_SetString(PyExc_ValueError, "list modified during sort");
2106 result = NULL;
2107 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 if (reverse && saved_ob_size > 1)
2110 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 merge_freemem(&ms);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002113
Daniel Stutzbach98338222010-12-02 21:55:33 +00002114keyfunc_fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 final_ob_item = self->ob_item;
2116 i = Py_SIZE(self);
2117 Py_SIZE(self) = saved_ob_size;
2118 self->ob_item = saved_ob_item;
2119 self->allocated = saved_allocated;
2120 if (final_ob_item != NULL) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002121 /* we cannot use _list_clear() for this because it does not
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002122 guarantee that the list is really empty when it returns */
2123 while (--i >= 0) {
2124 Py_XDECREF(final_ob_item[i]);
2125 }
2126 PyMem_FREE(final_ob_item);
2127 }
2128 Py_XINCREF(result);
2129 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002130}
Tim Peters330f9e92002-07-19 07:05:44 +00002131#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002132#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002133
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002134int
Fred Drakea2f55112000-07-09 15:16:51 +00002135PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002136{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 if (v == NULL || !PyList_Check(v)) {
2138 PyErr_BadInternalCall();
2139 return -1;
2140 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002141 v = list_sort_impl((PyListObject *)v, NULL, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 if (v == NULL)
2143 return -1;
2144 Py_DECREF(v);
2145 return 0;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002146}
2147
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002148/*[clinic input]
2149list.reverse
2150
2151Reverse *IN PLACE*.
2152[clinic start generated code]*/
2153
Guido van Rossumb86c5492001-02-12 22:06:02 +00002154static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002155list_reverse_impl(PyListObject *self)
2156/*[clinic end generated code: output=482544fc451abea9 input=eefd4c3ae1bc9887]*/
Guido van Rossumb86c5492001-02-12 22:06:02 +00002157{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 if (Py_SIZE(self) > 1)
2159 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
2160 Py_RETURN_NONE;
Guido van Rossumed98d481991-03-06 13:07:53 +00002161}
2162
Guido van Rossum84c76f51990-10-30 13:32:20 +00002163int
Fred Drakea2f55112000-07-09 15:16:51 +00002164PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002165{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 PyListObject *self = (PyListObject *)v;
Tim Peters6063e262002-08-08 01:06:39 +00002167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 if (v == NULL || !PyList_Check(v)) {
2169 PyErr_BadInternalCall();
2170 return -1;
2171 }
2172 if (Py_SIZE(self) > 1)
2173 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
2174 return 0;
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002175}
2176
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002177PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002178PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002179{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 PyObject *w;
2181 PyObject **p, **q;
2182 Py_ssize_t n;
2183 if (v == NULL || !PyList_Check(v)) {
2184 PyErr_BadInternalCall();
2185 return NULL;
2186 }
2187 n = Py_SIZE(v);
2188 w = PyTuple_New(n);
2189 if (w == NULL)
2190 return NULL;
2191 p = ((PyTupleObject *)w)->ob_item;
2192 q = ((PyListObject *)v)->ob_item;
2193 while (--n >= 0) {
2194 Py_INCREF(*q);
2195 *p = *q;
2196 p++;
2197 q++;
2198 }
2199 return w;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002200}
2201
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002202/*[clinic input]
2203list.index
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002204
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002205 value: object
Serhiy Storchaka80ec8362017-03-19 19:37:40 +02002206 start: slice_index(accept={int}) = 0
2207 stop: slice_index(accept={int}, c_default="PY_SSIZE_T_MAX") = sys.maxsize
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002208 /
2209
2210Return first index of value.
2211
2212Raises ValueError if the value is not present.
2213[clinic start generated code]*/
2214
2215static PyObject *
2216list_index_impl(PyListObject *self, PyObject *value, Py_ssize_t start,
2217 Py_ssize_t stop)
Serhiy Storchaka80ec8362017-03-19 19:37:40 +02002218/*[clinic end generated code: output=ec51b88787e4e481 input=40ec5826303a0eb1]*/
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002219{
2220 Py_ssize_t i;
2221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 if (start < 0) {
2223 start += Py_SIZE(self);
2224 if (start < 0)
2225 start = 0;
2226 }
2227 if (stop < 0) {
2228 stop += Py_SIZE(self);
2229 if (stop < 0)
2230 stop = 0;
2231 }
2232 for (i = start; i < stop && i < Py_SIZE(self); i++) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002233 int cmp = PyObject_RichCompareBool(self->ob_item[i], value, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 if (cmp > 0)
2235 return PyLong_FromSsize_t(i);
2236 else if (cmp < 0)
2237 return NULL;
2238 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002239 PyErr_Format(PyExc_ValueError, "%R is not in list", value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002241}
2242
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002243/*[clinic input]
2244list.count
2245
2246 value: object
2247 /
2248
2249Return number of occurrences of value.
2250[clinic start generated code]*/
2251
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002252static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002253list_count(PyListObject *self, PyObject *value)
2254/*[clinic end generated code: output=b1f5d284205ae714 input=3bdc3a5e6f749565]*/
Guido van Rossume6f7d181991-10-20 20:20:40 +00002255{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002256 Py_ssize_t count = 0;
2257 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 for (i = 0; i < Py_SIZE(self); i++) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002260 int cmp = PyObject_RichCompareBool(self->ob_item[i], value, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 if (cmp > 0)
2262 count++;
2263 else if (cmp < 0)
2264 return NULL;
2265 }
2266 return PyLong_FromSsize_t(count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002267}
2268
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002269/*[clinic input]
2270list.remove
2271
2272 value: object
2273 /
2274
2275Remove first occurrence of value.
2276
2277Raises ValueError if the value is not present.
2278[clinic start generated code]*/
2279
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002280static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002281list_remove(PyListObject *self, PyObject *value)
2282/*[clinic end generated code: output=f087e1951a5e30d1 input=2dc2ba5bb2fb1f82]*/
Guido van Rossumed98d481991-03-06 13:07:53 +00002283{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 for (i = 0; i < Py_SIZE(self); i++) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002287 int cmp = PyObject_RichCompareBool(self->ob_item[i], value, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 if (cmp > 0) {
2289 if (list_ass_slice(self, i, i+1,
2290 (PyObject *)NULL) == 0)
2291 Py_RETURN_NONE;
2292 return NULL;
2293 }
2294 else if (cmp < 0)
2295 return NULL;
2296 }
2297 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
2298 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002299}
2300
Jeremy Hylton8caad492000-06-23 14:18:11 +00002301static int
2302list_traverse(PyListObject *o, visitproc visit, void *arg)
2303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 Py_ssize_t i;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002306 for (i = Py_SIZE(o); --i >= 0; )
2307 Py_VISIT(o->ob_item[i]);
2308 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002309}
2310
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002311static PyObject *
2312list_richcompare(PyObject *v, PyObject *w, int op)
2313{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002314 PyListObject *vl, *wl;
2315 Py_ssize_t i;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002316
Brian Curtindfc80e32011-08-10 20:28:54 -05002317 if (!PyList_Check(v) || !PyList_Check(w))
2318 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 vl = (PyListObject *)v;
2321 wl = (PyListObject *)w;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) {
2324 /* Shortcut: if the lengths differ, the lists differ */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 if (op == Py_EQ)
stratakise8b19652017-11-02 11:32:54 +01002326 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 else
stratakise8b19652017-11-02 11:32:54 +01002328 Py_RETURN_TRUE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002329 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 /* Search for the first index where items are different */
2332 for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) {
2333 int k = PyObject_RichCompareBool(vl->ob_item[i],
2334 wl->ob_item[i], Py_EQ);
2335 if (k < 0)
2336 return NULL;
2337 if (!k)
2338 break;
2339 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) {
2342 /* No more items to compare -- compare sizes */
stratakise8b19652017-11-02 11:32:54 +01002343 Py_RETURN_RICHCOMPARE(Py_SIZE(vl), Py_SIZE(wl), op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002346 /* We have an item that differs -- shortcuts for EQ/NE */
2347 if (op == Py_EQ) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02002348 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 }
2350 if (op == Py_NE) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02002351 Py_RETURN_TRUE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 /* Compare the final item again using the proper operator */
2355 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002356}
2357
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002358/*[clinic input]
2359list.__init__
2360
2361 iterable: object(c_default="NULL") = ()
2362 /
2363
2364Built-in mutable sequence.
2365
2366If no argument is given, the constructor creates a new empty list.
2367The argument must be an iterable if specified.
2368[clinic start generated code]*/
2369
Tim Peters6d6c1a32001-08-02 04:15:00 +00002370static int
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002371list___init___impl(PyListObject *self, PyObject *iterable)
2372/*[clinic end generated code: output=0f3c21379d01de48 input=b3f3fe7206af8f6b]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +00002373{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 /* Verify list invariants established by PyType_GenericAlloc() */
2375 assert(0 <= Py_SIZE(self));
2376 assert(Py_SIZE(self) <= self->allocated || self->allocated == -1);
2377 assert(self->ob_item != NULL ||
2378 self->allocated == 0 || self->allocated == -1);
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 /* Empty previous contents */
2381 if (self->ob_item != NULL) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002382 (void)_list_clear(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002384 if (iterable != NULL) {
2385 PyObject *rv = list_extend(self, iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 if (rv == NULL)
2387 return -1;
2388 Py_DECREF(rv);
2389 }
2390 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002391}
2392
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002393/*[clinic input]
2394list.__sizeof__
2395
2396Return the size of the list in memory, in bytes.
2397[clinic start generated code]*/
2398
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002399static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002400list___sizeof___impl(PyListObject *self)
2401/*[clinic end generated code: output=3417541f95f9a53e input=b8030a5d5ce8a187]*/
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002402{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002403 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002404
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02002405 res = _PyObject_SIZE(Py_TYPE(self)) + self->allocated * sizeof(void*);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002407}
2408
Raymond Hettinger1021c442003-11-07 15:38:09 +00002409static PyObject *list_iter(PyObject *seq);
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002410static PyObject *list_subscript(PyListObject*, PyObject*);
2411
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002412static PyMethodDef list_methods[] = {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002413 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, "x.__getitem__(y) <==> x[y]"},
2414 LIST___REVERSED___METHODDEF
2415 LIST___SIZEOF___METHODDEF
2416 LIST_CLEAR_METHODDEF
2417 LIST_COPY_METHODDEF
2418 LIST_APPEND_METHODDEF
2419 LIST_INSERT_METHODDEF
2420 LIST_EXTEND_METHODDEF
2421 LIST_POP_METHODDEF
2422 LIST_REMOVE_METHODDEF
2423 LIST_INDEX_METHODDEF
2424 LIST_COUNT_METHODDEF
2425 LIST_REVERSE_METHODDEF
2426 LIST_SORT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002427 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002428};
2429
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002430static PySequenceMethods list_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002431 (lenfunc)list_length, /* sq_length */
2432 (binaryfunc)list_concat, /* sq_concat */
2433 (ssizeargfunc)list_repeat, /* sq_repeat */
2434 (ssizeargfunc)list_item, /* sq_item */
2435 0, /* sq_slice */
2436 (ssizeobjargproc)list_ass_item, /* sq_ass_item */
2437 0, /* sq_ass_slice */
2438 (objobjproc)list_contains, /* sq_contains */
2439 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
2440 (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002441};
2442
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002443static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002444list_subscript(PyListObject* self, PyObject* item)
2445{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 if (PyIndex_Check(item)) {
2447 Py_ssize_t i;
2448 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2449 if (i == -1 && PyErr_Occurred())
2450 return NULL;
2451 if (i < 0)
2452 i += PyList_GET_SIZE(self);
2453 return list_item(self, i);
2454 }
2455 else if (PySlice_Check(item)) {
2456 Py_ssize_t start, stop, step, slicelength, cur, i;
2457 PyObject* result;
2458 PyObject* it;
2459 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002460
Serhiy Storchakab879fe82017-04-08 09:53:51 +03002461 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002462 return NULL;
2463 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +03002464 slicelength = PySlice_AdjustIndices(Py_SIZE(self), &start, &stop,
2465 step);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002467 if (slicelength <= 0) {
2468 return PyList_New(0);
2469 }
2470 else if (step == 1) {
2471 return list_slice(self, start, stop);
2472 }
2473 else {
2474 result = PyList_New(slicelength);
2475 if (!result) return NULL;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002477 src = self->ob_item;
2478 dest = ((PyListObject *)result)->ob_item;
2479 for (cur = start, i = 0; i < slicelength;
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002480 cur += (size_t)step, i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002481 it = src[cur];
2482 Py_INCREF(it);
2483 dest[i] = it;
2484 }
Tim Peters3b01a122002-07-19 02:35:45 +00002485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 return result;
2487 }
2488 }
2489 else {
2490 PyErr_Format(PyExc_TypeError,
Terry Jan Reedyffff1442014-08-02 01:30:37 -04002491 "list indices must be integers or slices, not %.200s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002492 item->ob_type->tp_name);
2493 return NULL;
2494 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002495}
2496
Tim Peters3b01a122002-07-19 02:35:45 +00002497static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002498list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2499{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002500 if (PyIndex_Check(item)) {
2501 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2502 if (i == -1 && PyErr_Occurred())
2503 return -1;
2504 if (i < 0)
2505 i += PyList_GET_SIZE(self);
2506 return list_ass_item(self, i, value);
2507 }
2508 else if (PySlice_Check(item)) {
2509 Py_ssize_t start, stop, step, slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002510
Serhiy Storchakab879fe82017-04-08 09:53:51 +03002511 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002512 return -1;
2513 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +03002514 slicelength = PySlice_AdjustIndices(Py_SIZE(self), &start, &stop,
2515 step);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002517 if (step == 1)
2518 return list_ass_slice(self, start, stop, value);
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002520 /* Make sure s[5:2] = [..] inserts at the right place:
2521 before 5, not before 2. */
2522 if ((step < 0 && start < stop) ||
2523 (step > 0 && start > stop))
2524 stop = start;
Thomas Woutersed03b412007-08-28 21:37:11 +00002525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002526 if (value == NULL) {
2527 /* delete slice */
2528 PyObject **garbage;
2529 size_t cur;
2530 Py_ssize_t i;
Victor Stinner35f28032013-11-21 12:16:35 +01002531 int res;
Tim Peters3b01a122002-07-19 02:35:45 +00002532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 if (slicelength <= 0)
2534 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 if (step < 0) {
2537 stop = start + 1;
2538 start = stop + step*(slicelength - 1) - 1;
2539 step = -step;
2540 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002542 garbage = (PyObject**)
2543 PyMem_MALLOC(slicelength*sizeof(PyObject*));
2544 if (!garbage) {
2545 PyErr_NoMemory();
2546 return -1;
2547 }
Tim Peters3b01a122002-07-19 02:35:45 +00002548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002549 /* drawing pictures might help understand these for
2550 loops. Basically, we memmove the parts of the
2551 list that are *not* part of the slice: step-1
2552 items for each item that is part of the slice,
2553 and then tail end of the list that was not
2554 covered by the slice */
2555 for (cur = start, i = 0;
2556 cur < (size_t)stop;
2557 cur += step, i++) {
2558 Py_ssize_t lim = step - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002560 garbage[i] = PyList_GET_ITEM(self, cur);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 if (cur + step >= (size_t)Py_SIZE(self)) {
2563 lim = Py_SIZE(self) - cur - 1;
2564 }
Michael W. Hudson56796f62002-07-29 14:35:04 +00002565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002566 memmove(self->ob_item + cur - i,
2567 self->ob_item + cur + 1,
2568 lim * sizeof(PyObject *));
2569 }
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002570 cur = start + (size_t)slicelength * step;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002571 if (cur < (size_t)Py_SIZE(self)) {
2572 memmove(self->ob_item + cur - slicelength,
2573 self->ob_item + cur,
2574 (Py_SIZE(self) - cur) *
2575 sizeof(PyObject *));
2576 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002578 Py_SIZE(self) -= slicelength;
Victor Stinner35f28032013-11-21 12:16:35 +01002579 res = list_resize(self, Py_SIZE(self));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 for (i = 0; i < slicelength; i++) {
2582 Py_DECREF(garbage[i]);
2583 }
2584 PyMem_FREE(garbage);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002585
Victor Stinner35f28032013-11-21 12:16:35 +01002586 return res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002587 }
2588 else {
2589 /* assign slice */
2590 PyObject *ins, *seq;
2591 PyObject **garbage, **seqitems, **selfitems;
2592 Py_ssize_t cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002594 /* protect against a[::-1] = a */
2595 if (self == (PyListObject*)value) {
2596 seq = list_slice((PyListObject*)value, 0,
2597 PyList_GET_SIZE(value));
2598 }
2599 else {
2600 seq = PySequence_Fast(value,
2601 "must assign iterable "
2602 "to extended slice");
2603 }
2604 if (!seq)
2605 return -1;
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002607 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2608 PyErr_Format(PyExc_ValueError,
2609 "attempt to assign sequence of "
2610 "size %zd to extended slice of "
2611 "size %zd",
2612 PySequence_Fast_GET_SIZE(seq),
2613 slicelength);
2614 Py_DECREF(seq);
2615 return -1;
2616 }
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002618 if (!slicelength) {
2619 Py_DECREF(seq);
2620 return 0;
2621 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002623 garbage = (PyObject**)
2624 PyMem_MALLOC(slicelength*sizeof(PyObject*));
2625 if (!garbage) {
2626 Py_DECREF(seq);
2627 PyErr_NoMemory();
2628 return -1;
2629 }
Tim Peters3b01a122002-07-19 02:35:45 +00002630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 selfitems = self->ob_item;
2632 seqitems = PySequence_Fast_ITEMS(seq);
2633 for (cur = start, i = 0; i < slicelength;
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002634 cur += (size_t)step, i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002635 garbage[i] = selfitems[cur];
2636 ins = seqitems[i];
2637 Py_INCREF(ins);
2638 selfitems[cur] = ins;
2639 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002641 for (i = 0; i < slicelength; i++) {
2642 Py_DECREF(garbage[i]);
2643 }
Tim Peters3b01a122002-07-19 02:35:45 +00002644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002645 PyMem_FREE(garbage);
2646 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002648 return 0;
2649 }
2650 }
2651 else {
2652 PyErr_Format(PyExc_TypeError,
Terry Jan Reedyffff1442014-08-02 01:30:37 -04002653 "list indices must be integers or slices, not %.200s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002654 item->ob_type->tp_name);
2655 return -1;
2656 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002657}
2658
2659static PyMappingMethods list_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002660 (lenfunc)list_length,
2661 (binaryfunc)list_subscript,
2662 (objobjargproc)list_ass_subscript
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002663};
2664
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002665PyTypeObject PyList_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002666 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2667 "list",
2668 sizeof(PyListObject),
2669 0,
2670 (destructor)list_dealloc, /* tp_dealloc */
2671 0, /* tp_print */
2672 0, /* tp_getattr */
2673 0, /* tp_setattr */
2674 0, /* tp_reserved */
2675 (reprfunc)list_repr, /* tp_repr */
2676 0, /* tp_as_number */
2677 &list_as_sequence, /* tp_as_sequence */
2678 &list_as_mapping, /* tp_as_mapping */
Georg Brandl00da4e02010-10-18 07:32:48 +00002679 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002680 0, /* tp_call */
2681 0, /* tp_str */
2682 PyObject_GenericGetAttr, /* tp_getattro */
2683 0, /* tp_setattro */
2684 0, /* tp_as_buffer */
2685 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002686 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */
2687 list___init____doc__, /* tp_doc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002688 (traverseproc)list_traverse, /* tp_traverse */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002689 (inquiry)_list_clear, /* tp_clear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002690 list_richcompare, /* tp_richcompare */
2691 0, /* tp_weaklistoffset */
2692 list_iter, /* tp_iter */
2693 0, /* tp_iternext */
2694 list_methods, /* tp_methods */
2695 0, /* tp_members */
2696 0, /* tp_getset */
2697 0, /* tp_base */
2698 0, /* tp_dict */
2699 0, /* tp_descr_get */
2700 0, /* tp_descr_set */
2701 0, /* tp_dictoffset */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002702 (initproc)list___init__, /* tp_init */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002703 PyType_GenericAlloc, /* tp_alloc */
2704 PyType_GenericNew, /* tp_new */
2705 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002706};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002707
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002708/*********************** List Iterator **************************/
2709
2710typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002711 PyObject_HEAD
Victor Stinner7660b882013-06-24 23:59:24 +02002712 Py_ssize_t it_index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002713 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002714} listiterobject;
2715
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002716static void listiter_dealloc(listiterobject *);
2717static int listiter_traverse(listiterobject *, visitproc, void *);
2718static PyObject *listiter_next(listiterobject *);
2719static PyObject *listiter_len(listiterobject *);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002720static PyObject *listiter_reduce_general(void *_it, int forward);
2721static PyObject *listiter_reduce(listiterobject *);
2722static PyObject *listiter_setstate(listiterobject *, PyObject *state);
Raymond Hettinger435bf582004-03-18 22:43:10 +00002723
Armin Rigof5b3e362006-02-11 21:32:43 +00002724PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002725PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
2726PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002727
2728static PyMethodDef listiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002729 {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002730 {"__reduce__", (PyCFunction)listiter_reduce, METH_NOARGS, reduce_doc},
2731 {"__setstate__", (PyCFunction)listiter_setstate, METH_O, setstate_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002732 {NULL, NULL} /* sentinel */
Raymond Hettinger435bf582004-03-18 22:43:10 +00002733};
2734
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002735PyTypeObject PyListIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002736 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2737 "list_iterator", /* tp_name */
2738 sizeof(listiterobject), /* tp_basicsize */
2739 0, /* tp_itemsize */
2740 /* methods */
2741 (destructor)listiter_dealloc, /* tp_dealloc */
2742 0, /* tp_print */
2743 0, /* tp_getattr */
2744 0, /* tp_setattr */
2745 0, /* tp_reserved */
2746 0, /* tp_repr */
2747 0, /* tp_as_number */
2748 0, /* tp_as_sequence */
2749 0, /* tp_as_mapping */
2750 0, /* tp_hash */
2751 0, /* tp_call */
2752 0, /* tp_str */
2753 PyObject_GenericGetAttr, /* tp_getattro */
2754 0, /* tp_setattro */
2755 0, /* tp_as_buffer */
2756 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2757 0, /* tp_doc */
2758 (traverseproc)listiter_traverse, /* tp_traverse */
2759 0, /* tp_clear */
2760 0, /* tp_richcompare */
2761 0, /* tp_weaklistoffset */
2762 PyObject_SelfIter, /* tp_iter */
2763 (iternextfunc)listiter_next, /* tp_iternext */
2764 listiter_methods, /* tp_methods */
2765 0, /* tp_members */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002766};
Raymond Hettinger1021c442003-11-07 15:38:09 +00002767
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002768
2769static PyObject *
2770list_iter(PyObject *seq)
2771{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002772 listiterobject *it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002774 if (!PyList_Check(seq)) {
2775 PyErr_BadInternalCall();
2776 return NULL;
2777 }
2778 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2779 if (it == NULL)
2780 return NULL;
2781 it->it_index = 0;
2782 Py_INCREF(seq);
2783 it->it_seq = (PyListObject *)seq;
2784 _PyObject_GC_TRACK(it);
2785 return (PyObject *)it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002786}
2787
2788static void
2789listiter_dealloc(listiterobject *it)
2790{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002791 _PyObject_GC_UNTRACK(it);
2792 Py_XDECREF(it->it_seq);
2793 PyObject_GC_Del(it);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002794}
2795
2796static int
2797listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2798{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002799 Py_VISIT(it->it_seq);
2800 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002801}
2802
2803static PyObject *
2804listiter_next(listiterobject *it)
2805{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002806 PyListObject *seq;
2807 PyObject *item;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002809 assert(it != NULL);
2810 seq = it->it_seq;
2811 if (seq == NULL)
2812 return NULL;
2813 assert(PyList_Check(seq));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002815 if (it->it_index < PyList_GET_SIZE(seq)) {
2816 item = PyList_GET_ITEM(seq, it->it_index);
2817 ++it->it_index;
2818 Py_INCREF(item);
2819 return item;
2820 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002822 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03002823 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002824 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002825}
2826
2827static PyObject *
2828listiter_len(listiterobject *it)
2829{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002830 Py_ssize_t len;
2831 if (it->it_seq) {
2832 len = PyList_GET_SIZE(it->it_seq) - it->it_index;
2833 if (len >= 0)
2834 return PyLong_FromSsize_t(len);
2835 }
2836 return PyLong_FromLong(0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002837}
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002838
2839static PyObject *
2840listiter_reduce(listiterobject *it)
2841{
2842 return listiter_reduce_general(it, 1);
2843}
2844
2845static PyObject *
2846listiter_setstate(listiterobject *it, PyObject *state)
2847{
Victor Stinner7660b882013-06-24 23:59:24 +02002848 Py_ssize_t index = PyLong_AsSsize_t(state);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002849 if (index == -1 && PyErr_Occurred())
2850 return NULL;
2851 if (it->it_seq != NULL) {
2852 if (index < 0)
2853 index = 0;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +00002854 else if (index > PyList_GET_SIZE(it->it_seq))
2855 index = PyList_GET_SIZE(it->it_seq); /* iterator exhausted */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002856 it->it_index = index;
2857 }
2858 Py_RETURN_NONE;
2859}
2860
Raymond Hettinger1021c442003-11-07 15:38:09 +00002861/*********************** List Reverse Iterator **************************/
2862
2863typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002864 PyObject_HEAD
2865 Py_ssize_t it_index;
2866 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002867} listreviterobject;
2868
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002869static void listreviter_dealloc(listreviterobject *);
2870static int listreviter_traverse(listreviterobject *, visitproc, void *);
2871static PyObject *listreviter_next(listreviterobject *);
Raymond Hettingerf5b64112008-12-02 21:33:45 +00002872static PyObject *listreviter_len(listreviterobject *);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002873static PyObject *listreviter_reduce(listreviterobject *);
2874static PyObject *listreviter_setstate(listreviterobject *, PyObject *);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002875
Raymond Hettingerf5b64112008-12-02 21:33:45 +00002876static PyMethodDef listreviter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002877 {"__length_hint__", (PyCFunction)listreviter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002878 {"__reduce__", (PyCFunction)listreviter_reduce, METH_NOARGS, reduce_doc},
2879 {"__setstate__", (PyCFunction)listreviter_setstate, METH_O, setstate_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002880 {NULL, NULL} /* sentinel */
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002881};
2882
Raymond Hettinger1021c442003-11-07 15:38:09 +00002883PyTypeObject PyListRevIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002884 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2885 "list_reverseiterator", /* tp_name */
2886 sizeof(listreviterobject), /* tp_basicsize */
2887 0, /* tp_itemsize */
2888 /* methods */
2889 (destructor)listreviter_dealloc, /* tp_dealloc */
2890 0, /* tp_print */
2891 0, /* tp_getattr */
2892 0, /* tp_setattr */
2893 0, /* tp_reserved */
2894 0, /* tp_repr */
2895 0, /* tp_as_number */
2896 0, /* tp_as_sequence */
2897 0, /* tp_as_mapping */
2898 0, /* tp_hash */
2899 0, /* tp_call */
2900 0, /* tp_str */
2901 PyObject_GenericGetAttr, /* tp_getattro */
2902 0, /* tp_setattro */
2903 0, /* tp_as_buffer */
2904 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2905 0, /* tp_doc */
2906 (traverseproc)listreviter_traverse, /* tp_traverse */
2907 0, /* tp_clear */
2908 0, /* tp_richcompare */
2909 0, /* tp_weaklistoffset */
2910 PyObject_SelfIter, /* tp_iter */
2911 (iternextfunc)listreviter_next, /* tp_iternext */
2912 listreviter_methods, /* tp_methods */
2913 0,
Raymond Hettinger1021c442003-11-07 15:38:09 +00002914};
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002915
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002916/*[clinic input]
2917list.__reversed__
2918
2919Return a reverse iterator over the list.
2920[clinic start generated code]*/
2921
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002922static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002923list___reversed___impl(PyListObject *self)
2924/*[clinic end generated code: output=b166f073208c888c input=eadb6e17f8a6a280]*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002925{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002926 listreviterobject *it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002928 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
2929 if (it == NULL)
2930 return NULL;
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002931 assert(PyList_Check(self));
2932 it->it_index = PyList_GET_SIZE(self) - 1;
2933 Py_INCREF(self);
2934 it->it_seq = self;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002935 PyObject_GC_Track(it);
2936 return (PyObject *)it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002937}
2938
2939static void
2940listreviter_dealloc(listreviterobject *it)
2941{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002942 PyObject_GC_UnTrack(it);
2943 Py_XDECREF(it->it_seq);
2944 PyObject_GC_Del(it);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002945}
2946
2947static int
2948listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
2949{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002950 Py_VISIT(it->it_seq);
2951 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002952}
2953
2954static PyObject *
2955listreviter_next(listreviterobject *it)
2956{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002957 PyObject *item;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03002958 Py_ssize_t index;
2959 PyListObject *seq;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002960
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03002961 assert(it != NULL);
2962 seq = it->it_seq;
2963 if (seq == NULL) {
2964 return NULL;
2965 }
2966 assert(PyList_Check(seq));
2967
2968 index = it->it_index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002969 if (index>=0 && index < PyList_GET_SIZE(seq)) {
2970 item = PyList_GET_ITEM(seq, index);
2971 it->it_index--;
2972 Py_INCREF(item);
2973 return item;
2974 }
2975 it->it_index = -1;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03002976 it->it_seq = NULL;
2977 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002978 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002979}
2980
Raymond Hettingerf5b64112008-12-02 21:33:45 +00002981static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002982listreviter_len(listreviterobject *it)
2983{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002984 Py_ssize_t len = it->it_index + 1;
2985 if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
2986 len = 0;
2987 return PyLong_FromSsize_t(len);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002988}
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002989
2990static PyObject *
2991listreviter_reduce(listreviterobject *it)
2992{
2993 return listiter_reduce_general(it, 0);
2994}
2995
2996static PyObject *
2997listreviter_setstate(listreviterobject *it, PyObject *state)
2998{
2999 Py_ssize_t index = PyLong_AsSsize_t(state);
3000 if (index == -1 && PyErr_Occurred())
3001 return NULL;
3002 if (it->it_seq != NULL) {
3003 if (index < -1)
3004 index = -1;
3005 else if (index > PyList_GET_SIZE(it->it_seq) - 1)
3006 index = PyList_GET_SIZE(it->it_seq) - 1;
3007 it->it_index = index;
3008 }
3009 Py_RETURN_NONE;
3010}
3011
3012/* common pickling support */
3013
3014static PyObject *
3015listiter_reduce_general(void *_it, int forward)
3016{
3017 PyObject *list;
3018
3019 /* the objects are not the same, index is of different types! */
3020 if (forward) {
3021 listiterobject *it = (listiterobject *)_it;
3022 if (it->it_seq)
Victor Stinner7660b882013-06-24 23:59:24 +02003023 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003024 it->it_seq, it->it_index);
3025 } else {
3026 listreviterobject *it = (listreviterobject *)_it;
3027 if (it->it_seq)
Antoine Pitroua7013882012-04-05 00:04:20 +02003028 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("reversed"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003029 it->it_seq, it->it_index);
3030 }
3031 /* empty iterator, create an empty list */
3032 list = PyList_New(0);
3033 if (list == NULL)
3034 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +02003035 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), list);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003036}