blob: 858532252e92a7f2787018d163857dea8db33cef [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{
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +030088 PyObject *xoptions, *value;
89 _Py_IDENTIFIER(showalloccount);
90
91 xoptions = PySys_GetXOptions();
92 if (xoptions == NULL)
93 return;
94 value = _PyDict_GetItemId(xoptions, &PyId_showalloccount);
95 if (value != Py_True)
96 return;
97
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000098 fprintf(stderr, "List allocations: %" PY_FORMAT_SIZE_T "d\n",
99 count_alloc);
100 fprintf(stderr, "List reuse through freelist: %" PY_FORMAT_SIZE_T
101 "d\n", count_reuse);
102 fprintf(stderr, "%.2f%% reuse rate\n\n",
103 (100.0*count_reuse/(count_alloc+count_reuse)));
Christian Heimes77c02eb2008-02-09 02:18:51 +0000104}
105#endif
106
Raymond Hettinger0468e412004-05-05 05:37:53 +0000107/* Empty list reuse scheme to save calls to malloc and free */
Christian Heimes2202f872008-02-06 14:31:34 +0000108#ifndef PyList_MAXFREELIST
109#define PyList_MAXFREELIST 80
110#endif
111static PyListObject *free_list[PyList_MAXFREELIST];
112static int numfree = 0;
Raymond Hettinger0468e412004-05-05 05:37:53 +0000113
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100114int
115PyList_ClearFreeList(void)
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000116{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000117 PyListObject *op;
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100118 int ret = numfree;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000119 while (numfree) {
120 op = free_list[--numfree];
121 assert(PyList_CheckExact(op));
122 PyObject_GC_Del(op);
123 }
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100124 return ret;
125}
126
127void
128PyList_Fini(void)
129{
130 PyList_ClearFreeList();
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000131}
132
David Malcolm49526f42012-06-22 14:55:41 -0400133/* Print summary info about the state of the optimized allocator */
134void
135_PyList_DebugMallocStats(FILE *out)
136{
137 _PyDebugAllocatorStats(out,
138 "free PyListObject",
139 numfree, sizeof(PyListObject));
140}
141
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000142PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000143PyList_New(Py_ssize_t size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000145 PyListObject *op;
Christian Heimes77c02eb2008-02-09 02:18:51 +0000146#ifdef SHOW_ALLOC_COUNT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000147 static int initialized = 0;
148 if (!initialized) {
149 Py_AtExit(show_alloc);
150 initialized = 1;
151 }
Christian Heimes77c02eb2008-02-09 02:18:51 +0000152#endif
Tim Peters3986d4e2004-07-29 02:28:42 +0000153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 if (size < 0) {
155 PyErr_BadInternalCall();
156 return NULL;
157 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 if (numfree) {
159 numfree--;
160 op = free_list[numfree];
161 _Py_NewReference((PyObject *)op);
Christian Heimes77c02eb2008-02-09 02:18:51 +0000162#ifdef SHOW_ALLOC_COUNT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000163 count_reuse++;
Christian Heimes77c02eb2008-02-09 02:18:51 +0000164#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 } else {
166 op = PyObject_GC_New(PyListObject, &PyList_Type);
167 if (op == NULL)
168 return NULL;
Christian Heimes77c02eb2008-02-09 02:18:51 +0000169#ifdef SHOW_ALLOC_COUNT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000170 count_alloc++;
Christian Heimes77c02eb2008-02-09 02:18:51 +0000171#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000172 }
173 if (size <= 0)
174 op->ob_item = NULL;
175 else {
Mark Dickinson5d132382016-08-21 08:55:15 +0100176 op->ob_item = (PyObject **) PyMem_Calloc(size, sizeof(PyObject *));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000177 if (op->ob_item == NULL) {
178 Py_DECREF(op);
179 return PyErr_NoMemory();
180 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000181 }
182 Py_SIZE(op) = size;
183 op->allocated = size;
184 _PyObject_GC_TRACK(op);
185 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000186}
187
Martin v. Löwis18e16552006-02-15 17:27:45 +0000188Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000189PyList_Size(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000190{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 if (!PyList_Check(op)) {
192 PyErr_BadInternalCall();
193 return -1;
194 }
195 else
196 return Py_SIZE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000197}
198
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000199static PyObject *indexerr = NULL;
Guido van Rossum929f1b81996-08-09 20:51:27 +0000200
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000201PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000202PyList_GetItem(PyObject *op, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000203{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 if (!PyList_Check(op)) {
205 PyErr_BadInternalCall();
206 return NULL;
207 }
208 if (i < 0 || i >= Py_SIZE(op)) {
209 if (indexerr == NULL) {
210 indexerr = PyUnicode_FromString(
211 "list index out of range");
212 if (indexerr == NULL)
213 return NULL;
214 }
215 PyErr_SetObject(PyExc_IndexError, indexerr);
216 return NULL;
217 }
218 return ((PyListObject *)op) -> ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000219}
220
221int
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200222PyList_SetItem(PyObject *op, Py_ssize_t i,
223 PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000224{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200225 PyObject **p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 if (!PyList_Check(op)) {
227 Py_XDECREF(newitem);
228 PyErr_BadInternalCall();
229 return -1;
230 }
231 if (i < 0 || i >= Py_SIZE(op)) {
232 Py_XDECREF(newitem);
233 PyErr_SetString(PyExc_IndexError,
234 "list assignment index out of range");
235 return -1;
236 }
237 p = ((PyListObject *)op) -> ob_item + i;
Serhiy Storchakaec397562016-04-06 09:50:03 +0300238 Py_XSETREF(*p, newitem);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000240}
241
242static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000243ins1(PyListObject *self, Py_ssize_t where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000244{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 Py_ssize_t i, n = Py_SIZE(self);
246 PyObject **items;
247 if (v == NULL) {
248 PyErr_BadInternalCall();
249 return -1;
250 }
251 if (n == PY_SSIZE_T_MAX) {
252 PyErr_SetString(PyExc_OverflowError,
253 "cannot add more objects to list");
254 return -1;
255 }
Tim Petersb38e2b62004-07-29 02:29:26 +0000256
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800257 if (list_resize(self, n+1) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 return -1;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 if (where < 0) {
261 where += n;
262 if (where < 0)
263 where = 0;
264 }
265 if (where > n)
266 where = n;
267 items = self->ob_item;
268 for (i = n; --i >= where; )
269 items[i+1] = items[i];
270 Py_INCREF(v);
271 items[where] = v;
272 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000273}
274
275int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000276PyList_Insert(PyObject *op, Py_ssize_t where, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000277{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 if (!PyList_Check(op)) {
279 PyErr_BadInternalCall();
280 return -1;
281 }
282 return ins1((PyListObject *)op, where, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000283}
284
Raymond Hettinger40a03822004-04-12 13:05:09 +0000285static int
286app1(PyListObject *self, PyObject *v)
287{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 Py_ssize_t n = PyList_GET_SIZE(self);
Raymond Hettinger40a03822004-04-12 13:05:09 +0000289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 assert (v != NULL);
291 if (n == PY_SSIZE_T_MAX) {
292 PyErr_SetString(PyExc_OverflowError,
293 "cannot add more objects to list");
294 return -1;
295 }
Raymond Hettinger40a03822004-04-12 13:05:09 +0000296
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800297 if (list_resize(self, n+1) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 return -1;
Raymond Hettinger40a03822004-04-12 13:05:09 +0000299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 Py_INCREF(v);
301 PyList_SET_ITEM(self, n, v);
302 return 0;
Raymond Hettinger40a03822004-04-12 13:05:09 +0000303}
304
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000305int
Fred Drakea2f55112000-07-09 15:16:51 +0000306PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000307{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 if (PyList_Check(op) && (newitem != NULL))
309 return app1((PyListObject *)op, newitem);
310 PyErr_BadInternalCall();
311 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000312}
313
314/* Methods */
315
316static void
Fred Drakea2f55112000-07-09 15:16:51 +0000317list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000318{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 Py_ssize_t i;
320 PyObject_GC_UnTrack(op);
321 Py_TRASHCAN_SAFE_BEGIN(op)
322 if (op->ob_item != NULL) {
323 /* Do it backwards, for Christian Tismer.
324 There's a simple test case where somehow this reduces
325 thrashing when a *very* large list is created and
326 immediately deleted. */
327 i = Py_SIZE(op);
328 while (--i >= 0) {
329 Py_XDECREF(op->ob_item[i]);
330 }
331 PyMem_FREE(op->ob_item);
332 }
333 if (numfree < PyList_MAXFREELIST && PyList_CheckExact(op))
334 free_list[numfree++] = op;
335 else
336 Py_TYPE(op)->tp_free((PyObject *)op);
337 Py_TRASHCAN_SAFE_END(op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000338}
339
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000340static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000341list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000342{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 Py_ssize_t i;
Victor Stinner5c733472013-11-18 21:11:57 +0100344 PyObject *s;
Victor Stinner5c733472013-11-18 21:11:57 +0100345 _PyUnicodeWriter writer;
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200346
347 if (Py_SIZE(v) == 0) {
348 return PyUnicode_FromString("[]");
349 }
350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 i = Py_ReprEnter((PyObject*)v);
352 if (i != 0) {
353 return i > 0 ? PyUnicode_FromString("[...]") : NULL;
354 }
Tim Petersa7259592001-06-16 05:11:17 +0000355
Victor Stinner5c733472013-11-18 21:11:57 +0100356 _PyUnicodeWriter_Init(&writer);
357 writer.overallocate = 1;
Victor Stinnerb8fb1972013-11-18 22:15:44 +0100358 /* "[" + "1" + ", 2" * (len - 1) + "]" */
359 writer.min_length = 1 + 1 + (2 + 1) * (Py_SIZE(v) - 1) + 1;
Tim Petersa7259592001-06-16 05:11:17 +0000360
Victor Stinner5c733472013-11-18 21:11:57 +0100361 if (_PyUnicodeWriter_WriteChar(&writer, '[') < 0)
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200362 goto error;
Tim Petersa7259592001-06-16 05:11:17 +0000363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 /* Do repr() on each element. Note that this may mutate the list,
365 so must refetch the list size on each iteration. */
366 for (i = 0; i < Py_SIZE(v); ++i) {
Victor Stinner5c733472013-11-18 21:11:57 +0100367 if (i > 0) {
Victor Stinner4a587072013-11-19 12:54:53 +0100368 if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0)
Victor Stinner5c733472013-11-18 21:11:57 +0100369 goto error;
370 }
371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 if (Py_EnterRecursiveCall(" while getting the repr of a list"))
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200373 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 s = PyObject_Repr(v->ob_item[i]);
375 Py_LeaveRecursiveCall();
Victor Stinner5c733472013-11-18 21:11:57 +0100376 if (s == NULL)
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200377 goto error;
Victor Stinner5c733472013-11-18 21:11:57 +0100378
379 if (_PyUnicodeWriter_WriteStr(&writer, s) < 0) {
380 Py_DECREF(s);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200381 goto error;
Victor Stinner5c733472013-11-18 21:11:57 +0100382 }
383 Py_DECREF(s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 }
Victor Stinner5c733472013-11-18 21:11:57 +0100385
Victor Stinner4d3f1092013-11-19 12:09:00 +0100386 writer.overallocate = 0;
Victor Stinner5c733472013-11-18 21:11:57 +0100387 if (_PyUnicodeWriter_WriteChar(&writer, ']') < 0)
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200388 goto error;
Tim Petersa7259592001-06-16 05:11:17 +0000389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 Py_ReprLeave((PyObject *)v);
Victor Stinner5c733472013-11-18 21:11:57 +0100391 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200392
393error:
Victor Stinner5c733472013-11-18 21:11:57 +0100394 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200395 Py_ReprLeave((PyObject *)v);
396 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000397}
398
Martin v. Löwis18e16552006-02-15 17:27:45 +0000399static Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000400list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000401{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 return Py_SIZE(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000403}
404
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000405static int
Fred Drakea2f55112000-07-09 15:16:51 +0000406list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 Py_ssize_t i;
409 int cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i)
412 cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
413 Py_EQ);
414 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000415}
416
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000417static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000418list_item(PyListObject *a, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000419{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 if (i < 0 || i >= Py_SIZE(a)) {
421 if (indexerr == NULL) {
422 indexerr = PyUnicode_FromString(
423 "list index out of range");
424 if (indexerr == NULL)
425 return NULL;
426 }
427 PyErr_SetObject(PyExc_IndexError, indexerr);
428 return NULL;
429 }
430 Py_INCREF(a->ob_item[i]);
431 return a->ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000432}
433
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000434static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000435list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000436{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 PyListObject *np;
438 PyObject **src, **dest;
439 Py_ssize_t i, len;
440 if (ilow < 0)
441 ilow = 0;
442 else if (ilow > Py_SIZE(a))
443 ilow = Py_SIZE(a);
444 if (ihigh < ilow)
445 ihigh = ilow;
446 else if (ihigh > Py_SIZE(a))
447 ihigh = Py_SIZE(a);
448 len = ihigh - ilow;
449 np = (PyListObject *) PyList_New(len);
450 if (np == NULL)
451 return NULL;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 src = a->ob_item + ilow;
454 dest = np->ob_item;
455 for (i = 0; i < len; i++) {
456 PyObject *v = src[i];
457 Py_INCREF(v);
458 dest[i] = v;
459 }
460 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000461}
462
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000463PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000464PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 if (!PyList_Check(a)) {
467 PyErr_BadInternalCall();
468 return NULL;
469 }
470 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000471}
472
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000473static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000474list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000475{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 Py_ssize_t size;
477 Py_ssize_t i;
478 PyObject **src, **dest;
479 PyListObject *np;
480 if (!PyList_Check(bb)) {
481 PyErr_Format(PyExc_TypeError,
482 "can only concatenate list (not \"%.200s\") to list",
483 bb->ob_type->tp_name);
484 return NULL;
485 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000486#define b ((PyListObject *)bb)
Martin Panterb93d8632016-07-25 02:39:20 +0000487 if (Py_SIZE(a) > PY_SSIZE_T_MAX - Py_SIZE(b))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 return PyErr_NoMemory();
Martin Panterb93d8632016-07-25 02:39:20 +0000489 size = Py_SIZE(a) + Py_SIZE(b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 np = (PyListObject *) PyList_New(size);
491 if (np == NULL) {
492 return NULL;
493 }
494 src = a->ob_item;
495 dest = np->ob_item;
496 for (i = 0; i < Py_SIZE(a); i++) {
497 PyObject *v = src[i];
498 Py_INCREF(v);
499 dest[i] = v;
500 }
501 src = b->ob_item;
502 dest = np->ob_item + Py_SIZE(a);
503 for (i = 0; i < Py_SIZE(b); i++) {
504 PyObject *v = src[i];
505 Py_INCREF(v);
506 dest[i] = v;
507 }
508 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000509#undef b
510}
511
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000512static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000513list_repeat(PyListObject *a, Py_ssize_t n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000514{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 Py_ssize_t i, j;
516 Py_ssize_t size;
517 PyListObject *np;
518 PyObject **p, **items;
519 PyObject *elem;
520 if (n < 0)
521 n = 0;
Mark Dickinsonc0420fd2011-09-19 19:18:37 +0100522 if (n > 0 && Py_SIZE(a) > PY_SSIZE_T_MAX / n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 return PyErr_NoMemory();
Mark Dickinsonc0420fd2011-09-19 19:18:37 +0100524 size = Py_SIZE(a) * n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 if (size == 0)
526 return PyList_New(0);
527 np = (PyListObject *) PyList_New(size);
528 if (np == NULL)
529 return NULL;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 items = np->ob_item;
532 if (Py_SIZE(a) == 1) {
533 elem = a->ob_item[0];
534 for (i = 0; i < n; i++) {
535 items[i] = elem;
536 Py_INCREF(elem);
537 }
538 return (PyObject *) np;
539 }
540 p = np->ob_item;
541 items = a->ob_item;
542 for (i = 0; i < n; i++) {
543 for (j = 0; j < Py_SIZE(a); j++) {
544 *p = items[j];
545 Py_INCREF(*p);
546 p++;
547 }
548 }
549 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000550}
551
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000552static int
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200553_list_clear(PyListObject *a)
Armin Rigo93677f02004-07-29 12:40:23 +0000554{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 Py_ssize_t i;
556 PyObject **item = a->ob_item;
557 if (item != NULL) {
558 /* Because XDECREF can recursively invoke operations on
559 this list, we make it empty first. */
560 i = Py_SIZE(a);
561 Py_SIZE(a) = 0;
562 a->ob_item = NULL;
563 a->allocated = 0;
564 while (--i >= 0) {
565 Py_XDECREF(item[i]);
566 }
567 PyMem_FREE(item);
568 }
569 /* Never fails; the return value can be ignored.
570 Note that there is no guarantee that the list is actually empty
571 at this point, because XDECREF may have populated it again! */
572 return 0;
Armin Rigo93677f02004-07-29 12:40:23 +0000573}
574
Tim Peters8fc4a912004-07-31 21:53:19 +0000575/* a[ilow:ihigh] = v if v != NULL.
576 * del a[ilow:ihigh] if v == NULL.
577 *
578 * Special speed gimmick: when v is NULL and ihigh - ilow <= 8, it's
579 * guaranteed the call cannot fail.
580 */
Armin Rigo93677f02004-07-29 12:40:23 +0000581static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000582list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000583{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 /* Because [X]DECREF can recursively invoke list operations on
585 this list, we must postpone all [X]DECREF activity until
586 after the list is back in its canonical shape. Therefore
587 we must allocate an additional array, 'recycle', into which
588 we temporarily copy the items that are deleted from the
589 list. :-( */
590 PyObject *recycle_on_stack[8];
591 PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
592 PyObject **item;
593 PyObject **vitem = NULL;
594 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
595 Py_ssize_t n; /* # of elements in replacement list */
596 Py_ssize_t norig; /* # of elements in list getting replaced */
597 Py_ssize_t d; /* Change in size */
598 Py_ssize_t k;
599 size_t s;
600 int result = -1; /* guilty until proved innocent */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000601#define b ((PyListObject *)v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 if (v == NULL)
603 n = 0;
604 else {
605 if (a == b) {
606 /* Special case "a[i:j] = a" -- copy b first */
607 v = list_slice(b, 0, Py_SIZE(b));
608 if (v == NULL)
609 return result;
610 result = list_ass_slice(a, ilow, ihigh, v);
611 Py_DECREF(v);
612 return result;
613 }
614 v_as_SF = PySequence_Fast(v, "can only assign an iterable");
615 if(v_as_SF == NULL)
616 goto Error;
617 n = PySequence_Fast_GET_SIZE(v_as_SF);
618 vitem = PySequence_Fast_ITEMS(v_as_SF);
619 }
620 if (ilow < 0)
621 ilow = 0;
622 else if (ilow > Py_SIZE(a))
623 ilow = Py_SIZE(a);
Tim Peters8d9eb102004-07-31 02:24:20 +0000624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 if (ihigh < ilow)
626 ihigh = ilow;
627 else if (ihigh > Py_SIZE(a))
628 ihigh = Py_SIZE(a);
Armin Rigo93677f02004-07-29 12:40:23 +0000629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 norig = ihigh - ilow;
631 assert(norig >= 0);
632 d = n - norig;
633 if (Py_SIZE(a) + d == 0) {
634 Py_XDECREF(v_as_SF);
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200635 return _list_clear(a);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 }
637 item = a->ob_item;
638 /* recycle the items that we are about to remove */
639 s = norig * sizeof(PyObject *);
Benjamin Peterson5a7d9232016-09-06 17:58:25 -0700640 /* If norig == 0, item might be NULL, in which case we may not memcpy from it. */
641 if (s) {
642 if (s > sizeof(recycle_on_stack)) {
643 recycle = (PyObject **)PyMem_MALLOC(s);
644 if (recycle == NULL) {
645 PyErr_NoMemory();
646 goto Error;
647 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 }
Benjamin Peterson5a7d9232016-09-06 17:58:25 -0700649 memcpy(recycle, &item[ilow], s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 }
Tim Peters8d9eb102004-07-31 02:24:20 +0000651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 if (d < 0) { /* Delete -d items */
Victor Stinner2c40f642013-07-19 23:06:21 +0200653 Py_ssize_t tail;
654 tail = (Py_SIZE(a) - ihigh) * sizeof(PyObject *);
655 memmove(&item[ihigh+d], &item[ihigh], tail);
656 if (list_resize(a, Py_SIZE(a) + d) < 0) {
657 memmove(&item[ihigh], &item[ihigh+d], tail);
658 memcpy(&item[ilow], recycle, s);
659 goto Error;
660 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 item = a->ob_item;
662 }
663 else if (d > 0) { /* Insert d items */
664 k = Py_SIZE(a);
665 if (list_resize(a, k+d) < 0)
666 goto Error;
667 item = a->ob_item;
668 memmove(&item[ihigh+d], &item[ihigh],
669 (k - ihigh)*sizeof(PyObject *));
670 }
671 for (k = 0; k < n; k++, ilow++) {
672 PyObject *w = vitem[k];
673 Py_XINCREF(w);
674 item[ilow] = w;
675 }
676 for (k = norig - 1; k >= 0; --k)
677 Py_XDECREF(recycle[k]);
678 result = 0;
Tim Peters8d9eb102004-07-31 02:24:20 +0000679 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 if (recycle != recycle_on_stack)
681 PyMem_FREE(recycle);
682 Py_XDECREF(v_as_SF);
683 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000684#undef b
685}
686
Guido van Rossum234f9421993-06-17 12:35:49 +0000687int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000688PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 if (!PyList_Check(a)) {
691 PyErr_BadInternalCall();
692 return -1;
693 }
694 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000695}
696
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000697static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000698list_inplace_repeat(PyListObject *self, Py_ssize_t n)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000699{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 PyObject **items;
701 Py_ssize_t size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000702
703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 size = PyList_GET_SIZE(self);
705 if (size == 0 || n == 1) {
706 Py_INCREF(self);
707 return (PyObject *)self;
708 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 if (n < 1) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200711 (void)_list_clear(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 Py_INCREF(self);
713 return (PyObject *)self;
714 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 if (size > PY_SSIZE_T_MAX / n) {
717 return PyErr_NoMemory();
718 }
Christian Heimesaf98da12008-01-27 15:18:18 +0000719
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800720 if (list_resize(self, size*n) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 return NULL;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723 p = size;
724 items = self->ob_item;
725 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
726 for (j = 0; j < size; j++) {
727 PyObject *o = items[j];
728 Py_INCREF(o);
729 items[p++] = o;
730 }
731 }
732 Py_INCREF(self);
733 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000734}
735
Guido van Rossum4a450d01991-04-03 19:05:18 +0000736static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000737list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000738{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 if (i < 0 || i >= Py_SIZE(a)) {
740 PyErr_SetString(PyExc_IndexError,
741 "list assignment index out of range");
742 return -1;
743 }
744 if (v == NULL)
745 return list_ass_slice(a, i, i+1, v);
746 Py_INCREF(v);
Serhiy Storchakaf01e4082016-04-10 18:12:01 +0300747 Py_SETREF(a->ob_item[i], v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 return 0;
Guido van Rossum4a450d01991-04-03 19:05:18 +0000749}
750
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200751/*[clinic input]
752list.insert
753
754 index: Py_ssize_t
755 object: object
756 /
757
758Insert object before index.
759[clinic start generated code]*/
760
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000761static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200762list_insert_impl(PyListObject *self, Py_ssize_t index, PyObject *object)
763/*[clinic end generated code: output=7f35e32f60c8cb78 input=858514cf894c7eab]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000764{
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200765 if (ins1(self, index, object) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 Py_RETURN_NONE;
767 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000768}
769
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200770/*[clinic input]
771list.clear
772
773Remove all items from list.
774[clinic start generated code]*/
775
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000776static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200777list_clear_impl(PyListObject *self)
778/*[clinic end generated code: output=67a1896c01f74362 input=ca3c1646856742f6]*/
Eli Benderskycbbaa962011-02-25 05:47:53 +0000779{
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200780 _list_clear(self);
Eli Benderskycbbaa962011-02-25 05:47:53 +0000781 Py_RETURN_NONE;
782}
783
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200784/*[clinic input]
785list.copy
786
787Return a shallow copy of the list.
788[clinic start generated code]*/
789
Eli Benderskycbbaa962011-02-25 05:47:53 +0000790static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200791list_copy_impl(PyListObject *self)
792/*[clinic end generated code: output=ec6b72d6209d418e input=6453ab159e84771f]*/
Eli Benderskycbbaa962011-02-25 05:47:53 +0000793{
794 return list_slice(self, 0, Py_SIZE(self));
795}
796
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200797/*[clinic input]
798list.append
799
800 object: object
801 /
802
803Append object to the end of the list.
804[clinic start generated code]*/
805
Eli Benderskycbbaa962011-02-25 05:47:53 +0000806static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200807list_append(PyListObject *self, PyObject *object)
808/*[clinic end generated code: output=7c096003a29c0eae input=43a3fe48a7066e91]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000809{
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200810 if (app1(self, object) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 Py_RETURN_NONE;
812 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000813}
814
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200815/*[clinic input]
816list.extend
817
818 iterable: object
819 /
820
821Extend list by appending elements from the iterable.
822[clinic start generated code]*/
823
Barry Warsawdedf6d61998-10-09 16:37:25 +0000824static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200825list_extend(PyListObject *self, PyObject *iterable)
826/*[clinic end generated code: output=630fb3bca0c8e789 input=9ec5ba3a81be3a4d]*/
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000827{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 PyObject *it; /* iter(v) */
829 Py_ssize_t m; /* size of self */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200830 Py_ssize_t n; /* guess for size of iterable */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 Py_ssize_t mn; /* m + n */
832 Py_ssize_t i;
833 PyObject *(*iternext)(PyObject *);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 /* Special cases:
836 1) lists and tuples which can use PySequence_Fast ops
837 2) extending self to self requires making a copy first
838 */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200839 if (PyList_CheckExact(iterable) || PyTuple_CheckExact(iterable) ||
840 (PyObject *)self == iterable) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 PyObject **src, **dest;
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200842 iterable = PySequence_Fast(iterable, "argument must be iterable");
843 if (!iterable)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 return NULL;
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200845 n = PySequence_Fast_GET_SIZE(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 if (n == 0) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200847 /* short circuit when iterable is empty */
848 Py_DECREF(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 Py_RETURN_NONE;
850 }
851 m = Py_SIZE(self);
Martin Panter94b39ce2017-01-14 06:30:37 +0000852 /* It should not be possible to allocate a list large enough to cause
853 an overflow on any relevant platform */
854 assert(m < PY_SSIZE_T_MAX - n);
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800855 if (list_resize(self, m + n) < 0) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200856 Py_DECREF(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 return NULL;
858 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200859 /* note that we may still have self == iterable here for the
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 * situation a.extend(a), but the following code works
861 * in that case too. Just make sure to resize self
862 * before calling PySequence_Fast_ITEMS.
863 */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200864 /* populate the end of self with iterable's items */
865 src = PySequence_Fast_ITEMS(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 dest = self->ob_item + m;
867 for (i = 0; i < n; i++) {
868 PyObject *o = src[i];
869 Py_INCREF(o);
870 dest[i] = o;
871 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200872 Py_DECREF(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 Py_RETURN_NONE;
874 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000875
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200876 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 if (it == NULL)
878 return NULL;
879 iternext = *it->ob_type->tp_iternext;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 /* Guess a result list size. */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200882 n = PyObject_LengthHint(iterable, 8);
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800883 if (n < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 Py_DECREF(it);
885 return NULL;
886 }
887 m = Py_SIZE(self);
Martin Panterb93d8632016-07-25 02:39:20 +0000888 if (m > PY_SSIZE_T_MAX - n) {
889 /* m + n overflowed; on the chance that n lied, and there really
890 * is enough room, ignore it. If n was telling the truth, we'll
891 * eventually run out of memory during the loop.
892 */
893 }
894 else {
895 mn = m + n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 /* Make room. */
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800897 if (list_resize(self, mn) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 goto error;
899 /* Make the list sane again. */
900 Py_SIZE(self) = m;
901 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 /* Run iterator to exhaustion. */
904 for (;;) {
905 PyObject *item = iternext(it);
906 if (item == NULL) {
907 if (PyErr_Occurred()) {
908 if (PyErr_ExceptionMatches(PyExc_StopIteration))
909 PyErr_Clear();
910 else
911 goto error;
912 }
913 break;
914 }
915 if (Py_SIZE(self) < self->allocated) {
916 /* steals ref */
917 PyList_SET_ITEM(self, Py_SIZE(self), item);
918 ++Py_SIZE(self);
919 }
920 else {
921 int status = app1(self, item);
922 Py_DECREF(item); /* append creates a new ref */
923 if (status < 0)
924 goto error;
925 }
926 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 /* Cut back result list if initial guess was too large. */
Victor Stinner32fd6ea2013-07-16 21:45:58 +0200929 if (Py_SIZE(self) < self->allocated) {
930 if (list_resize(self, Py_SIZE(self)) < 0)
931 goto error;
932 }
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 Py_DECREF(it);
935 Py_RETURN_NONE;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000936
937 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 Py_DECREF(it);
939 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000940}
941
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000942PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200943_PyList_Extend(PyListObject *self, PyObject *iterable)
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000944{
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200945 return list_extend(self, iterable);
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000946}
947
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000948static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000949list_inplace_concat(PyListObject *self, PyObject *other)
950{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 PyObject *result;
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000952
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200953 result = list_extend(self, other);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 if (result == NULL)
955 return result;
956 Py_DECREF(result);
957 Py_INCREF(self);
958 return (PyObject *)self;
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000959}
960
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200961/*[clinic input]
962list.pop
963
964 index: Py_ssize_t = -1
965 /
966
967Remove and return item at index (default last).
968
969Raises IndexError if list is empty or index is out of range.
970[clinic start generated code]*/
971
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000972static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200973list_pop_impl(PyListObject *self, Py_ssize_t index)
974/*[clinic end generated code: output=6bd69dcb3f17eca8 input=b83675976f329e6f]*/
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000975{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 PyObject *v;
977 int status;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 if (Py_SIZE(self) == 0) {
980 /* Special-case most common failure cause */
981 PyErr_SetString(PyExc_IndexError, "pop from empty list");
982 return NULL;
983 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200984 if (index < 0)
985 index += Py_SIZE(self);
986 if (index < 0 || index >= Py_SIZE(self)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 PyErr_SetString(PyExc_IndexError, "pop index out of range");
988 return NULL;
989 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200990 v = self->ob_item[index];
991 if (index == Py_SIZE(self) - 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 status = list_resize(self, Py_SIZE(self) - 1);
Victor Stinnerb27cd3e2013-07-08 22:20:44 +0200993 if (status >= 0)
994 return v; /* and v now owns the reference the list had */
995 else
996 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 }
998 Py_INCREF(v);
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200999 status = list_ass_slice(self, index, index+1, (PyObject *)NULL);
Victor Stinner095d99f2013-07-17 21:58:01 +02001000 if (status < 0) {
1001 Py_DECREF(v);
1002 return NULL;
1003 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 return v;
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00001005}
1006
Tim Peters8e2e7ca2002-07-19 02:33:08 +00001007/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
1008static void
1009reverse_slice(PyObject **lo, PyObject **hi)
1010{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 assert(lo && hi);
Tim Peters8e2e7ca2002-07-19 02:33:08 +00001012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 --hi;
1014 while (lo < hi) {
1015 PyObject *t = *lo;
1016 *lo = *hi;
1017 *hi = t;
1018 ++lo;
1019 --hi;
1020 }
Tim Peters8e2e7ca2002-07-19 02:33:08 +00001021}
1022
Tim Petersa64dc242002-08-01 02:13:36 +00001023/* Lots of code for an adaptive, stable, natural mergesort. There are many
1024 * pieces to this algorithm; read listsort.txt for overviews and details.
1025 */
Guido van Rossum3f236de1996-12-10 23:55:39 +00001026
Daniel Stutzbach98338222010-12-02 21:55:33 +00001027/* A sortslice contains a pointer to an array of keys and a pointer to
1028 * an array of corresponding values. In other words, keys[i]
1029 * corresponds with values[i]. If values == NULL, then the keys are
1030 * also the values.
1031 *
1032 * Several convenience routines are provided here, so that keys and
1033 * values are always moved in sync.
1034 */
1035
1036typedef struct {
1037 PyObject **keys;
1038 PyObject **values;
1039} sortslice;
1040
1041Py_LOCAL_INLINE(void)
1042sortslice_copy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j)
1043{
1044 s1->keys[i] = s2->keys[j];
1045 if (s1->values != NULL)
1046 s1->values[i] = s2->values[j];
1047}
1048
1049Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001050sortslice_copy_incr(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
1057Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001058sortslice_copy_decr(sortslice *dst, sortslice *src)
1059{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001060 *dst->keys-- = *src->keys--;
1061 if (dst->values != NULL)
1062 *dst->values-- = *src->values--;
1063}
1064
1065
1066Py_LOCAL_INLINE(void)
1067sortslice_memcpy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j,
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001068 Py_ssize_t n)
1069{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001070 memcpy(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
1071 if (s1->values != NULL)
1072 memcpy(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
1073}
1074
1075Py_LOCAL_INLINE(void)
1076sortslice_memmove(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j,
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001077 Py_ssize_t n)
1078{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001079 memmove(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
1080 if (s1->values != NULL)
1081 memmove(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
1082}
1083
1084Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001085sortslice_advance(sortslice *slice, Py_ssize_t n)
1086{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001087 slice->keys += n;
1088 if (slice->values != NULL)
1089 slice->values += n;
1090}
1091
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001092/* Comparison function: PyObject_RichCompareBool with Py_LT.
Tim Petersa64dc242002-08-01 02:13:36 +00001093 * Returns -1 on error, 1 if x < y, 0 if x >= y.
1094 */
Guido van Rossum3f236de1996-12-10 23:55:39 +00001095
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001096#define ISLT(X, Y) (PyObject_RichCompareBool(X, Y, Py_LT))
Tim Peters66860f62002-08-04 17:47:26 +00001097
1098/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +00001099 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
1100 started. It makes more sense in context <wink>. X and Y are PyObject*s.
1101*/
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001102#define IFLT(X, Y) if ((k = ISLT(X, Y)) < 0) goto fail; \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001104
1105/* binarysort is the best method for sorting small arrays: it does
1106 few compares, but can do data movement quadratic in the number of
1107 elements.
Guido van Rossum42812581998-06-17 14:15:44 +00001108 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +00001109 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001110 On entry, must have lo <= start <= hi, and that [lo, start) is already
1111 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +00001112 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001113 Even in case of error, the output slice will be some permutation of
1114 the input (nothing is lost or duplicated).
1115*/
Guido van Rossum3f236de1996-12-10 23:55:39 +00001116static int
Daniel Stutzbach98338222010-12-02 21:55:33 +00001117binarysort(sortslice lo, PyObject **hi, PyObject **start)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001118{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001119 Py_ssize_t k;
1120 PyObject **l, **p, **r;
1121 PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001122
Daniel Stutzbach98338222010-12-02 21:55:33 +00001123 assert(lo.keys <= start && start <= hi);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 /* assert [lo, start) is sorted */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001125 if (lo.keys == start)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 ++start;
1127 for (; start < hi; ++start) {
1128 /* set l to where *start belongs */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001129 l = lo.keys;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 r = start;
1131 pivot = *r;
1132 /* Invariants:
1133 * pivot >= all in [lo, l).
1134 * pivot < all in [r, start).
1135 * The second is vacuously true at the start.
1136 */
1137 assert(l < r);
1138 do {
1139 p = l + ((r - l) >> 1);
1140 IFLT(pivot, *p)
1141 r = p;
1142 else
1143 l = p+1;
1144 } while (l < r);
1145 assert(l == r);
1146 /* The invariants still hold, so pivot >= all in [lo, l) and
1147 pivot < all in [l, start), so pivot belongs at l. Note
1148 that if there are elements equal to pivot, l points to the
1149 first slot after them -- that's why this sort is stable.
1150 Slide over to make room.
1151 Caution: using memmove is much slower under MSVC 5;
1152 we're not usually moving many slots. */
1153 for (p = start; p > l; --p)
1154 *p = *(p-1);
1155 *l = pivot;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001156 if (lo.values != NULL) {
1157 Py_ssize_t offset = lo.values - lo.keys;
1158 p = start + offset;
1159 pivot = *p;
1160 l += offset;
1161 for (p = start + offset; p > l; --p)
1162 *p = *(p-1);
1163 *l = pivot;
1164 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 }
1166 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001167
1168 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001170}
1171
Tim Petersa64dc242002-08-01 02:13:36 +00001172/*
1173Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
1174is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001175
Tim Petersa64dc242002-08-01 02:13:36 +00001176 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001177
Tim Petersa64dc242002-08-01 02:13:36 +00001178or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001179
Tim Petersa64dc242002-08-01 02:13:36 +00001180 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +00001181
Tim Petersa64dc242002-08-01 02:13:36 +00001182Boolean *descending is set to 0 in the former case, or to 1 in the latter.
1183For its intended use in a stable mergesort, the strictness of the defn of
1184"descending" is needed so that the caller can safely reverse a descending
1185sequence without violating stability (strict > ensures there are no equal
1186elements to get out of order).
1187
1188Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001189*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001190static Py_ssize_t
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001191count_run(PyObject **lo, PyObject **hi, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001192{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 Py_ssize_t k;
1194 Py_ssize_t n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 assert(lo < hi);
1197 *descending = 0;
1198 ++lo;
1199 if (lo == hi)
1200 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 n = 2;
1203 IFLT(*lo, *(lo-1)) {
1204 *descending = 1;
1205 for (lo = lo+1; lo < hi; ++lo, ++n) {
1206 IFLT(*lo, *(lo-1))
1207 ;
1208 else
1209 break;
1210 }
1211 }
1212 else {
1213 for (lo = lo+1; lo < hi; ++lo, ++n) {
1214 IFLT(*lo, *(lo-1))
1215 break;
1216 }
1217 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 return n;
Tim Petersa64dc242002-08-01 02:13:36 +00001220fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001221 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001222}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001223
Tim Petersa64dc242002-08-01 02:13:36 +00001224/*
1225Locate the proper position of key in a sorted vector; if the vector contains
1226an element equal to key, return the position immediately to the left of
1227the leftmost equal element. [gallop_right() does the same except returns
1228the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001229
Tim Petersa64dc242002-08-01 02:13:36 +00001230"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001231
Tim Petersa64dc242002-08-01 02:13:36 +00001232"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1233hint is to the final result, the faster this runs.
1234
1235The return value is the int k in 0..n such that
1236
1237 a[k-1] < key <= a[k]
1238
1239pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1240key belongs at index k; or, IOW, the first k elements of a should precede
1241key, and the last n-k should follow key.
1242
1243Returns -1 on error. See listsort.txt for info on the method.
1244*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001245static Py_ssize_t
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001246gallop_left(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
Tim Petersa64dc242002-08-01 02:13:36 +00001247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 Py_ssize_t ofs;
1249 Py_ssize_t lastofs;
1250 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 assert(key && a && n > 0 && hint >= 0 && hint < n);
Tim Petersa64dc242002-08-01 02:13:36 +00001253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 a += hint;
1255 lastofs = 0;
1256 ofs = 1;
1257 IFLT(*a, key) {
1258 /* a[hint] < key -- gallop right, until
1259 * a[hint + lastofs] < key <= a[hint + ofs]
1260 */
1261 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
1262 while (ofs < maxofs) {
1263 IFLT(a[ofs], key) {
1264 lastofs = ofs;
1265 ofs = (ofs << 1) + 1;
1266 if (ofs <= 0) /* int overflow */
1267 ofs = maxofs;
1268 }
1269 else /* key <= a[hint + ofs] */
1270 break;
1271 }
1272 if (ofs > maxofs)
1273 ofs = maxofs;
1274 /* Translate back to offsets relative to &a[0]. */
1275 lastofs += hint;
1276 ofs += hint;
1277 }
1278 else {
1279 /* key <= a[hint] -- gallop left, until
1280 * a[hint - ofs] < key <= a[hint - lastofs]
1281 */
1282 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
1283 while (ofs < maxofs) {
1284 IFLT(*(a-ofs), key)
1285 break;
1286 /* key <= a[hint - ofs] */
1287 lastofs = ofs;
1288 ofs = (ofs << 1) + 1;
1289 if (ofs <= 0) /* int overflow */
1290 ofs = maxofs;
1291 }
1292 if (ofs > maxofs)
1293 ofs = maxofs;
1294 /* Translate back to positive offsets relative to &a[0]. */
1295 k = lastofs;
1296 lastofs = hint - ofs;
1297 ofs = hint - k;
1298 }
1299 a -= hint;
Tim Petersa64dc242002-08-01 02:13:36 +00001300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1302 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1303 * right of lastofs but no farther right than ofs. Do a binary
1304 * search, with invariant a[lastofs-1] < key <= a[ofs].
1305 */
1306 ++lastofs;
1307 while (lastofs < ofs) {
1308 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 IFLT(a[m], key)
1311 lastofs = m+1; /* a[m] < key */
1312 else
1313 ofs = m; /* key <= a[m] */
1314 }
1315 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1316 return ofs;
Tim Petersa64dc242002-08-01 02:13:36 +00001317
1318fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001320}
1321
1322/*
1323Exactly like gallop_left(), except that if key already exists in a[0:n],
1324finds the position immediately to the right of the rightmost equal value.
1325
1326The return value is the int k in 0..n such that
1327
1328 a[k-1] <= key < a[k]
1329
1330or -1 if error.
1331
1332The code duplication is massive, but this is enough different given that
1333we're sticking to "<" comparisons that it's much harder to follow if
1334written as one routine with yet another "left or right?" flag.
1335*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001336static Py_ssize_t
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001337gallop_right(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
Tim Petersa64dc242002-08-01 02:13:36 +00001338{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 Py_ssize_t ofs;
1340 Py_ssize_t lastofs;
1341 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 assert(key && a && n > 0 && hint >= 0 && hint < n);
Tim Petersa64dc242002-08-01 02:13:36 +00001344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 a += hint;
1346 lastofs = 0;
1347 ofs = 1;
1348 IFLT(key, *a) {
1349 /* key < a[hint] -- gallop left, until
1350 * a[hint - ofs] <= key < a[hint - lastofs]
1351 */
1352 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
1353 while (ofs < maxofs) {
1354 IFLT(key, *(a-ofs)) {
1355 lastofs = ofs;
1356 ofs = (ofs << 1) + 1;
1357 if (ofs <= 0) /* int overflow */
1358 ofs = maxofs;
1359 }
1360 else /* a[hint - ofs] <= key */
1361 break;
1362 }
1363 if (ofs > maxofs)
1364 ofs = maxofs;
1365 /* Translate back to positive offsets relative to &a[0]. */
1366 k = lastofs;
1367 lastofs = hint - ofs;
1368 ofs = hint - k;
1369 }
1370 else {
1371 /* a[hint] <= key -- gallop right, until
1372 * a[hint + lastofs] <= key < a[hint + ofs]
1373 */
1374 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
1375 while (ofs < maxofs) {
1376 IFLT(key, a[ofs])
1377 break;
1378 /* a[hint + ofs] <= key */
1379 lastofs = ofs;
1380 ofs = (ofs << 1) + 1;
1381 if (ofs <= 0) /* int overflow */
1382 ofs = maxofs;
1383 }
1384 if (ofs > maxofs)
1385 ofs = maxofs;
1386 /* Translate back to offsets relative to &a[0]. */
1387 lastofs += hint;
1388 ofs += hint;
1389 }
1390 a -= hint;
Tim Petersa64dc242002-08-01 02:13:36 +00001391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1393 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1394 * right of lastofs but no farther right than ofs. Do a binary
1395 * search, with invariant a[lastofs-1] <= key < a[ofs].
1396 */
1397 ++lastofs;
1398 while (lastofs < ofs) {
1399 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 IFLT(key, a[m])
1402 ofs = m; /* key < a[m] */
1403 else
1404 lastofs = m+1; /* a[m] <= key */
1405 }
1406 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1407 return ofs;
Tim Petersa64dc242002-08-01 02:13:36 +00001408
1409fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001411}
1412
1413/* The maximum number of entries in a MergeState's pending-runs stack.
1414 * This is enough to sort arrays of size up to about
1415 * 32 * phi ** MAX_MERGE_PENDING
1416 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1417 * with 2**64 elements.
1418 */
1419#define MAX_MERGE_PENDING 85
1420
Tim Peterse05f65a2002-08-10 05:21:15 +00001421/* When we get into galloping mode, we stay there until both runs win less
1422 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
Tim Petersa64dc242002-08-01 02:13:36 +00001423 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001424#define MIN_GALLOP 7
Tim Petersa64dc242002-08-01 02:13:36 +00001425
1426/* Avoid malloc for small temp arrays. */
1427#define MERGESTATE_TEMP_SIZE 256
1428
1429/* One MergeState exists on the stack per invocation of mergesort. It's just
1430 * a convenient way to pass state around among the helper functions.
1431 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001432struct s_slice {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001433 sortslice base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 Py_ssize_t len;
Tim Peterse05f65a2002-08-10 05:21:15 +00001435};
1436
Tim Petersa64dc242002-08-01 02:13:36 +00001437typedef struct s_MergeState {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 /* This controls when we get *into* galloping mode. It's initialized
1439 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1440 * random data, and lower for highly structured data.
1441 */
1442 Py_ssize_t min_gallop;
Tim Peterse05f65a2002-08-10 05:21:15 +00001443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 /* 'a' is temp storage to help with merges. It contains room for
1445 * alloced entries.
1446 */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001447 sortslice a; /* may point to temparray below */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 Py_ssize_t alloced;
Tim Petersa64dc242002-08-01 02:13:36 +00001449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 /* A stack of n pending runs yet to be merged. Run #i starts at
1451 * address base[i] and extends for len[i] elements. It's always
1452 * true (so long as the indices are in bounds) that
1453 *
1454 * pending[i].base + pending[i].len == pending[i+1].base
1455 *
1456 * so we could cut the storage for this, but it's a minor amount,
1457 * and keeping all the info explicit simplifies the code.
1458 */
1459 int n;
1460 struct s_slice pending[MAX_MERGE_PENDING];
Tim Petersa64dc242002-08-01 02:13:36 +00001461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 /* 'a' points to this when possible, rather than muck with malloc. */
1463 PyObject *temparray[MERGESTATE_TEMP_SIZE];
Tim Petersa64dc242002-08-01 02:13:36 +00001464} MergeState;
1465
1466/* Conceptually a MergeState's constructor. */
1467static void
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001468merge_init(MergeState *ms, Py_ssize_t list_size, int has_keyfunc)
Tim Petersa64dc242002-08-01 02:13:36 +00001469{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 assert(ms != NULL);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001471 if (has_keyfunc) {
1472 /* The temporary space for merging will need at most half the list
1473 * size rounded up. Use the minimum possible space so we can use the
1474 * rest of temparray for other things. In particular, if there is
1475 * enough extra space, listsort() will use it to store the keys.
1476 */
1477 ms->alloced = (list_size + 1) / 2;
1478
1479 /* ms->alloced describes how many keys will be stored at
1480 ms->temparray, but we also need to store the values. Hence,
1481 ms->alloced is capped at half of MERGESTATE_TEMP_SIZE. */
1482 if (MERGESTATE_TEMP_SIZE / 2 < ms->alloced)
1483 ms->alloced = MERGESTATE_TEMP_SIZE / 2;
1484 ms->a.values = &ms->temparray[ms->alloced];
1485 }
1486 else {
1487 ms->alloced = MERGESTATE_TEMP_SIZE;
1488 ms->a.values = NULL;
1489 }
1490 ms->a.keys = ms->temparray;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001491 ms->n = 0;
1492 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001493}
1494
1495/* Free all the temp memory owned by the MergeState. This must be called
1496 * when you're done with a MergeState, and may be called before then if
1497 * you want to free the temp memory early.
1498 */
1499static void
1500merge_freemem(MergeState *ms)
1501{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001502 assert(ms != NULL);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001503 if (ms->a.keys != ms->temparray)
1504 PyMem_Free(ms->a.keys);
Tim Petersa64dc242002-08-01 02:13:36 +00001505}
1506
1507/* Ensure enough temp memory for 'need' array slots is available.
1508 * Returns 0 on success and -1 if the memory can't be gotten.
1509 */
1510static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001511merge_getmem(MergeState *ms, Py_ssize_t need)
Tim Petersa64dc242002-08-01 02:13:36 +00001512{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001513 int multiplier;
1514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 assert(ms != NULL);
1516 if (need <= ms->alloced)
1517 return 0;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001518
1519 multiplier = ms->a.values != NULL ? 2 : 1;
1520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001521 /* Don't realloc! That can cost cycles to copy the old data, but
1522 * we don't care what's in the block.
1523 */
1524 merge_freemem(ms);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001525 if ((size_t)need > PY_SSIZE_T_MAX / sizeof(PyObject*) / multiplier) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 PyErr_NoMemory();
1527 return -1;
1528 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001529 ms->a.keys = (PyObject**)PyMem_Malloc(multiplier * need
1530 * sizeof(PyObject *));
1531 if (ms->a.keys != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 ms->alloced = need;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001533 if (ms->a.values != NULL)
1534 ms->a.values = &ms->a.keys[need];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 return 0;
1536 }
1537 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001539}
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1541 merge_getmem(MS, NEED))
Tim Petersa64dc242002-08-01 02:13:36 +00001542
Daniel Stutzbach98338222010-12-02 21:55:33 +00001543/* Merge the na elements starting at ssa with the nb elements starting at
1544 * ssb.keys = ssa.keys + na in a stable way, in-place. na and nb must be > 0.
1545 * Must also have that ssa.keys[na-1] belongs at the end of the merge, and
1546 * should have na <= nb. See listsort.txt for more info. Return 0 if
1547 * successful, -1 if error.
Tim Petersa64dc242002-08-01 02:13:36 +00001548 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001549static Py_ssize_t
Daniel Stutzbach98338222010-12-02 21:55:33 +00001550merge_lo(MergeState *ms, sortslice ssa, Py_ssize_t na,
1551 sortslice ssb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001552{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 Py_ssize_t k;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001554 sortslice dest;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 int result = -1; /* guilty until proved innocent */
1556 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001557
Daniel Stutzbach98338222010-12-02 21:55:33 +00001558 assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
1559 assert(ssa.keys + na == ssb.keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 if (MERGE_GETMEM(ms, na) < 0)
1561 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001562 sortslice_memcpy(&ms->a, 0, &ssa, 0, na);
1563 dest = ssa;
1564 ssa = ms->a;
Tim Petersa64dc242002-08-01 02:13:36 +00001565
Daniel Stutzbach98338222010-12-02 21:55:33 +00001566 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 --nb;
1568 if (nb == 0)
1569 goto Succeed;
1570 if (na == 1)
1571 goto CopyB;
Tim Petersa64dc242002-08-01 02:13:36 +00001572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 min_gallop = ms->min_gallop;
1574 for (;;) {
1575 Py_ssize_t acount = 0; /* # of times A won in a row */
1576 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 /* Do the straightforward thing until (if ever) one run
1579 * appears to win consistently.
1580 */
1581 for (;;) {
1582 assert(na > 1 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001583 k = ISLT(ssb.keys[0], ssa.keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001584 if (k) {
1585 if (k < 0)
1586 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001587 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 ++bcount;
1589 acount = 0;
1590 --nb;
1591 if (nb == 0)
1592 goto Succeed;
1593 if (bcount >= min_gallop)
1594 break;
1595 }
1596 else {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001597 sortslice_copy_incr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 ++acount;
1599 bcount = 0;
1600 --na;
1601 if (na == 1)
1602 goto CopyB;
1603 if (acount >= min_gallop)
1604 break;
1605 }
1606 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 /* One run is winning so consistently that galloping may
1609 * be a huge win. So try that, and continue galloping until
1610 * (if ever) neither run appears to be winning consistently
1611 * anymore.
1612 */
1613 ++min_gallop;
1614 do {
1615 assert(na > 1 && nb > 0);
1616 min_gallop -= min_gallop > 1;
1617 ms->min_gallop = min_gallop;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001618 k = gallop_right(ssb.keys[0], ssa.keys, na, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 acount = k;
1620 if (k) {
1621 if (k < 0)
1622 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001623 sortslice_memcpy(&dest, 0, &ssa, 0, k);
1624 sortslice_advance(&dest, k);
1625 sortslice_advance(&ssa, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 na -= k;
1627 if (na == 1)
1628 goto CopyB;
1629 /* na==0 is impossible now if the comparison
1630 * function is consistent, but we can't assume
1631 * that it is.
1632 */
1633 if (na == 0)
1634 goto Succeed;
1635 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001636 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 --nb;
1638 if (nb == 0)
1639 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001640
Daniel Stutzbach98338222010-12-02 21:55:33 +00001641 k = gallop_left(ssa.keys[0], ssb.keys, nb, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 bcount = k;
1643 if (k) {
1644 if (k < 0)
1645 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001646 sortslice_memmove(&dest, 0, &ssb, 0, k);
1647 sortslice_advance(&dest, k);
1648 sortslice_advance(&ssb, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 nb -= k;
1650 if (nb == 0)
1651 goto Succeed;
1652 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001653 sortslice_copy_incr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 --na;
1655 if (na == 1)
1656 goto CopyB;
1657 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
1658 ++min_gallop; /* penalize it for leaving galloping mode */
1659 ms->min_gallop = min_gallop;
1660 }
Tim Petersa64dc242002-08-01 02:13:36 +00001661Succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 result = 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001663Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 if (na)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001665 sortslice_memcpy(&dest, 0, &ssa, 0, na);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001666 return result;
Tim Petersa64dc242002-08-01 02:13:36 +00001667CopyB:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001668 assert(na == 1 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001669 /* The last element of ssa belongs at the end of the merge. */
1670 sortslice_memmove(&dest, 0, &ssb, 0, nb);
1671 sortslice_copy(&dest, nb, &ssa, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001673}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001674
Daniel Stutzbach98338222010-12-02 21:55:33 +00001675/* Merge the na elements starting at pa with the nb elements starting at
1676 * ssb.keys = ssa.keys + na in a stable way, in-place. na and nb must be > 0.
1677 * Must also have that ssa.keys[na-1] belongs at the end of the merge, and
1678 * should have na >= nb. See listsort.txt for more info. Return 0 if
1679 * successful, -1 if error.
Tim Petersa64dc242002-08-01 02:13:36 +00001680 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001681static Py_ssize_t
Daniel Stutzbach98338222010-12-02 21:55:33 +00001682merge_hi(MergeState *ms, sortslice ssa, Py_ssize_t na,
1683 sortslice ssb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001684{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 Py_ssize_t k;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001686 sortslice dest, basea, baseb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 int result = -1; /* guilty until proved innocent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001689
Daniel Stutzbach98338222010-12-02 21:55:33 +00001690 assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
1691 assert(ssa.keys + na == ssb.keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 if (MERGE_GETMEM(ms, nb) < 0)
1693 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001694 dest = ssb;
1695 sortslice_advance(&dest, nb-1);
1696 sortslice_memcpy(&ms->a, 0, &ssb, 0, nb);
1697 basea = ssa;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 baseb = ms->a;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001699 ssb.keys = ms->a.keys + nb - 1;
1700 if (ssb.values != NULL)
1701 ssb.values = ms->a.values + nb - 1;
1702 sortslice_advance(&ssa, na - 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001703
Daniel Stutzbach98338222010-12-02 21:55:33 +00001704 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 --na;
1706 if (na == 0)
1707 goto Succeed;
1708 if (nb == 1)
1709 goto CopyA;
Tim Petersa64dc242002-08-01 02:13:36 +00001710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 min_gallop = ms->min_gallop;
1712 for (;;) {
1713 Py_ssize_t acount = 0; /* # of times A won in a row */
1714 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 /* Do the straightforward thing until (if ever) one run
1717 * appears to win consistently.
1718 */
1719 for (;;) {
1720 assert(na > 0 && nb > 1);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001721 k = ISLT(ssb.keys[0], ssa.keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 if (k) {
1723 if (k < 0)
1724 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001725 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 ++acount;
1727 bcount = 0;
1728 --na;
1729 if (na == 0)
1730 goto Succeed;
1731 if (acount >= min_gallop)
1732 break;
1733 }
1734 else {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001735 sortslice_copy_decr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 ++bcount;
1737 acount = 0;
1738 --nb;
1739 if (nb == 1)
1740 goto CopyA;
1741 if (bcount >= min_gallop)
1742 break;
1743 }
1744 }
Tim Petersa64dc242002-08-01 02:13:36 +00001745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 /* One run is winning so consistently that galloping may
1747 * be a huge win. So try that, and continue galloping until
1748 * (if ever) neither run appears to be winning consistently
1749 * anymore.
1750 */
1751 ++min_gallop;
1752 do {
1753 assert(na > 0 && nb > 1);
1754 min_gallop -= min_gallop > 1;
1755 ms->min_gallop = min_gallop;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001756 k = gallop_right(ssb.keys[0], basea.keys, na, na-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 if (k < 0)
1758 goto Fail;
1759 k = na - k;
1760 acount = k;
1761 if (k) {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001762 sortslice_advance(&dest, -k);
1763 sortslice_advance(&ssa, -k);
1764 sortslice_memmove(&dest, 1, &ssa, 1, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 na -= k;
1766 if (na == 0)
1767 goto Succeed;
1768 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001769 sortslice_copy_decr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 --nb;
1771 if (nb == 1)
1772 goto CopyA;
Tim Petersa64dc242002-08-01 02:13:36 +00001773
Daniel Stutzbach98338222010-12-02 21:55:33 +00001774 k = gallop_left(ssa.keys[0], baseb.keys, nb, nb-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 if (k < 0)
1776 goto Fail;
1777 k = nb - k;
1778 bcount = k;
1779 if (k) {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001780 sortslice_advance(&dest, -k);
1781 sortslice_advance(&ssb, -k);
1782 sortslice_memcpy(&dest, 1, &ssb, 1, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 nb -= k;
1784 if (nb == 1)
1785 goto CopyA;
1786 /* nb==0 is impossible now if the comparison
1787 * function is consistent, but we can't assume
1788 * that it is.
1789 */
1790 if (nb == 0)
1791 goto Succeed;
1792 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001793 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 --na;
1795 if (na == 0)
1796 goto Succeed;
1797 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
1798 ++min_gallop; /* penalize it for leaving galloping mode */
1799 ms->min_gallop = min_gallop;
1800 }
Tim Petersa64dc242002-08-01 02:13:36 +00001801Succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 result = 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001803Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 if (nb)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001805 sortslice_memcpy(&dest, -(nb-1), &baseb, 0, nb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 return result;
Tim Petersa64dc242002-08-01 02:13:36 +00001807CopyA:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 assert(nb == 1 && na > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001809 /* The first element of ssb belongs at the front of the merge. */
1810 sortslice_memmove(&dest, 1-na, &ssa, 1-na, na);
1811 sortslice_advance(&dest, -na);
1812 sortslice_advance(&ssa, -na);
1813 sortslice_copy(&dest, 0, &ssb, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001815}
1816
1817/* Merge the two runs at stack indices i and i+1.
1818 * Returns 0 on success, -1 on error.
1819 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001820static Py_ssize_t
1821merge_at(MergeState *ms, Py_ssize_t i)
Tim Petersa64dc242002-08-01 02:13:36 +00001822{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001823 sortslice ssa, ssb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 Py_ssize_t na, nb;
1825 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 assert(ms != NULL);
1828 assert(ms->n >= 2);
1829 assert(i >= 0);
1830 assert(i == ms->n - 2 || i == ms->n - 3);
Tim Petersa64dc242002-08-01 02:13:36 +00001831
Daniel Stutzbach98338222010-12-02 21:55:33 +00001832 ssa = ms->pending[i].base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 na = ms->pending[i].len;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001834 ssb = ms->pending[i+1].base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 nb = ms->pending[i+1].len;
1836 assert(na > 0 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001837 assert(ssa.keys + na == ssb.keys);
Tim Petersa64dc242002-08-01 02:13:36 +00001838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001839 /* Record the length of the combined runs; if i is the 3rd-last
1840 * run now, also slide over the last run (which isn't involved
1841 * in this merge). The current run i+1 goes away in any case.
1842 */
1843 ms->pending[i].len = na + nb;
1844 if (i == ms->n - 3)
1845 ms->pending[i+1] = ms->pending[i+2];
1846 --ms->n;
Tim Petersa64dc242002-08-01 02:13:36 +00001847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 /* Where does b start in a? Elements in a before that can be
1849 * ignored (already in place).
1850 */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001851 k = gallop_right(*ssb.keys, ssa.keys, na, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 if (k < 0)
1853 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001854 sortslice_advance(&ssa, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 na -= k;
1856 if (na == 0)
1857 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001859 /* Where does a end in b? Elements in b after that can be
1860 * ignored (already in place).
1861 */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001862 nb = gallop_left(ssa.keys[na-1], ssb.keys, nb, nb-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 if (nb <= 0)
1864 return nb;
Tim Petersa64dc242002-08-01 02:13:36 +00001865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 /* Merge what remains of the runs, using a temp array with
1867 * min(na, nb) elements.
1868 */
1869 if (na <= nb)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001870 return merge_lo(ms, ssa, na, ssb, nb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 else
Daniel Stutzbach98338222010-12-02 21:55:33 +00001872 return merge_hi(ms, ssa, na, ssb, nb);
Tim Petersa64dc242002-08-01 02:13:36 +00001873}
1874
1875/* Examine the stack of runs waiting to be merged, merging adjacent runs
1876 * until the stack invariants are re-established:
1877 *
1878 * 1. len[-3] > len[-2] + len[-1]
1879 * 2. len[-2] > len[-1]
1880 *
1881 * See listsort.txt for more info.
1882 *
1883 * Returns 0 on success, -1 on error.
1884 */
1885static int
1886merge_collapse(MergeState *ms)
1887{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 assert(ms);
1891 while (ms->n > 1) {
1892 Py_ssize_t n = ms->n - 2;
Benjamin Petersonb808d592015-02-25 10:12:26 -05001893 if ((n > 0 && p[n-1].len <= p[n].len + p[n+1].len) ||
1894 (n > 1 && p[n-2].len <= p[n-1].len + p[n].len)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 if (p[n-1].len < p[n+1].len)
1896 --n;
1897 if (merge_at(ms, n) < 0)
1898 return -1;
1899 }
1900 else if (p[n].len <= p[n+1].len) {
1901 if (merge_at(ms, n) < 0)
1902 return -1;
1903 }
1904 else
1905 break;
1906 }
1907 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001908}
1909
1910/* Regardless of invariants, merge all runs on the stack until only one
1911 * remains. This is used at the end of the mergesort.
1912 *
1913 * Returns 0 on success, -1 on error.
1914 */
1915static int
1916merge_force_collapse(MergeState *ms)
1917{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 assert(ms);
1921 while (ms->n > 1) {
1922 Py_ssize_t n = ms->n - 2;
1923 if (n > 0 && p[n-1].len < p[n+1].len)
1924 --n;
1925 if (merge_at(ms, n) < 0)
1926 return -1;
1927 }
1928 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001929}
1930
1931/* Compute a good value for the minimum run length; natural runs shorter
1932 * than this are boosted artificially via binary insertion.
1933 *
1934 * If n < 64, return n (it's too small to bother with fancy stuff).
1935 * Else if n is an exact power of 2, return 32.
1936 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1937 * strictly less than, an exact power of 2.
1938 *
1939 * See listsort.txt for more info.
1940 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001941static Py_ssize_t
1942merge_compute_minrun(Py_ssize_t n)
Tim Petersa64dc242002-08-01 02:13:36 +00001943{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001944 Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */
Tim Petersa64dc242002-08-01 02:13:36 +00001945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001946 assert(n >= 0);
1947 while (n >= 64) {
1948 r |= n & 1;
1949 n >>= 1;
1950 }
1951 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001952}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001953
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001954static void
Daniel Stutzbach98338222010-12-02 21:55:33 +00001955reverse_sortslice(sortslice *s, Py_ssize_t n)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001956{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001957 reverse_slice(s->keys, &s->keys[n]);
1958 if (s->values != NULL)
1959 reverse_slice(s->values, &s->values[n]);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001960}
1961
Tim Petersa64dc242002-08-01 02:13:36 +00001962/* An adaptive, stable, natural mergesort. See listsort.txt.
1963 * Returns Py_None on success, NULL on error. Even in case of error, the
1964 * list will be some permutation of its input state (nothing is lost or
1965 * duplicated).
1966 */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02001967/*[clinic input]
1968list.sort
1969
1970 *
1971 key as keyfunc: object = None
Serhiy Storchaka202fda52017-03-12 10:10:47 +02001972 reverse: bool(accept={int}) = False
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02001973
1974Stable sort *IN PLACE*.
1975[clinic start generated code]*/
1976
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001977static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02001978list_sort_impl(PyListObject *self, PyObject *keyfunc, int reverse)
Serhiy Storchaka202fda52017-03-12 10:10:47 +02001979/*[clinic end generated code: output=57b9f9c5e23fbe42 input=b0fcf743982c5b90]*/
Guido van Rossum3f236de1996-12-10 23:55:39 +00001980{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 MergeState ms;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 Py_ssize_t nremaining;
1983 Py_ssize_t minrun;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001984 sortslice lo;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 Py_ssize_t saved_ob_size, saved_allocated;
1986 PyObject **saved_ob_item;
1987 PyObject **final_ob_item;
1988 PyObject *result = NULL; /* guilty until proved innocent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 Py_ssize_t i;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001990 PyObject **keys;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 assert(self != NULL);
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02001993 assert(PyList_Check(self));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 if (keyfunc == Py_None)
1995 keyfunc = NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 /* The list is temporarily made empty, so that mutations performed
1998 * by comparison functions can't affect the slice of memory we're
1999 * sorting (allowing mutations during sorting is a core-dump
2000 * factory, since ob_item may change).
2001 */
2002 saved_ob_size = Py_SIZE(self);
2003 saved_ob_item = self->ob_item;
2004 saved_allocated = self->allocated;
2005 Py_SIZE(self) = 0;
2006 self->ob_item = NULL;
2007 self->allocated = -1; /* any operation will reset it to >= 0 */
Tim Peters330f9e92002-07-19 07:05:44 +00002008
Daniel Stutzbach98338222010-12-02 21:55:33 +00002009 if (keyfunc == NULL) {
2010 keys = NULL;
2011 lo.keys = saved_ob_item;
2012 lo.values = NULL;
2013 }
2014 else {
2015 if (saved_ob_size < MERGESTATE_TEMP_SIZE/2)
2016 /* Leverage stack space we allocated but won't otherwise use */
2017 keys = &ms.temparray[saved_ob_size+1];
2018 else {
2019 keys = PyMem_MALLOC(sizeof(PyObject *) * saved_ob_size);
Benjamin Peterson0823ffb2015-04-23 17:04:36 -04002020 if (keys == NULL) {
2021 PyErr_NoMemory();
2022 goto keyfunc_fail;
2023 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00002025
2026 for (i = 0; i < saved_ob_size ; i++) {
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01002027 keys[i] = PyObject_CallFunctionObjArgs(keyfunc, saved_ob_item[i],
2028 NULL);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002029 if (keys[i] == NULL) {
2030 for (i=i-1 ; i>=0 ; i--)
2031 Py_DECREF(keys[i]);
Benjamin Peterson4a42cd42014-03-15 12:21:28 -05002032 if (saved_ob_size >= MERGESTATE_TEMP_SIZE/2)
Daniel Stutzbach8eda5f72011-03-02 23:37:50 +00002033 PyMem_FREE(keys);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002034 goto keyfunc_fail;
2035 }
2036 }
2037
2038 lo.keys = keys;
2039 lo.values = saved_ob_item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002041
Daniel Stutzbach98338222010-12-02 21:55:33 +00002042 merge_init(&ms, saved_ob_size, keys != NULL);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002044 nremaining = saved_ob_size;
2045 if (nremaining < 2)
2046 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00002047
Benjamin Peterson05380642010-08-23 19:35:39 +00002048 /* Reverse sort stability achieved by initially reversing the list,
2049 applying a stable forward sort, then reversing the final result. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00002050 if (reverse) {
2051 if (keys != NULL)
2052 reverse_slice(&keys[0], &keys[saved_ob_size]);
2053 reverse_slice(&saved_ob_item[0], &saved_ob_item[saved_ob_size]);
2054 }
Benjamin Peterson05380642010-08-23 19:35:39 +00002055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 /* March over the array once, left to right, finding natural runs,
2057 * and extending short natural runs to minrun elements.
2058 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002059 minrun = merge_compute_minrun(nremaining);
2060 do {
2061 int descending;
2062 Py_ssize_t n;
Tim Peters330f9e92002-07-19 07:05:44 +00002063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 /* Identify next run. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00002065 n = count_run(lo.keys, lo.keys + nremaining, &descending);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 if (n < 0)
2067 goto fail;
2068 if (descending)
Daniel Stutzbach98338222010-12-02 21:55:33 +00002069 reverse_sortslice(&lo, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 /* If short, extend to min(minrun, nremaining). */
2071 if (n < minrun) {
2072 const Py_ssize_t force = nremaining <= minrun ?
2073 nremaining : minrun;
Daniel Stutzbach98338222010-12-02 21:55:33 +00002074 if (binarysort(lo, lo.keys + force, lo.keys + n) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 goto fail;
2076 n = force;
2077 }
2078 /* Push run onto pending-runs stack, and maybe merge. */
2079 assert(ms.n < MAX_MERGE_PENDING);
2080 ms.pending[ms.n].base = lo;
2081 ms.pending[ms.n].len = n;
2082 ++ms.n;
2083 if (merge_collapse(&ms) < 0)
2084 goto fail;
2085 /* Advance to find next run. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00002086 sortslice_advance(&lo, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002087 nremaining -= n;
2088 } while (nremaining);
Tim Peters330f9e92002-07-19 07:05:44 +00002089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002090 if (merge_force_collapse(&ms) < 0)
2091 goto fail;
2092 assert(ms.n == 1);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002093 assert(keys == NULL
2094 ? ms.pending[0].base.keys == saved_ob_item
2095 : ms.pending[0].base.keys == &keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 assert(ms.pending[0].len == saved_ob_size);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002097 lo = ms.pending[0].base;
Tim Petersa64dc242002-08-01 02:13:36 +00002098
2099succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00002101fail:
Daniel Stutzbach98338222010-12-02 21:55:33 +00002102 if (keys != NULL) {
2103 for (i = 0; i < saved_ob_size; i++)
2104 Py_DECREF(keys[i]);
Benjamin Petersonef87f8c2014-03-14 21:54:31 -05002105 if (saved_ob_size >= MERGESTATE_TEMP_SIZE/2)
Daniel Stutzbach98338222010-12-02 21:55:33 +00002106 PyMem_FREE(keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 if (self->allocated != -1 && result != NULL) {
2110 /* The user mucked with the list during the sort,
2111 * and we don't already have another error to report.
2112 */
2113 PyErr_SetString(PyExc_ValueError, "list modified during sort");
2114 result = NULL;
2115 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 if (reverse && saved_ob_size > 1)
2118 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 merge_freemem(&ms);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002121
Daniel Stutzbach98338222010-12-02 21:55:33 +00002122keyfunc_fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 final_ob_item = self->ob_item;
2124 i = Py_SIZE(self);
2125 Py_SIZE(self) = saved_ob_size;
2126 self->ob_item = saved_ob_item;
2127 self->allocated = saved_allocated;
2128 if (final_ob_item != NULL) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002129 /* we cannot use _list_clear() for this because it does not
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 guarantee that the list is really empty when it returns */
2131 while (--i >= 0) {
2132 Py_XDECREF(final_ob_item[i]);
2133 }
2134 PyMem_FREE(final_ob_item);
2135 }
2136 Py_XINCREF(result);
2137 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002138}
Tim Peters330f9e92002-07-19 07:05:44 +00002139#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002140#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002141
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002142int
Fred Drakea2f55112000-07-09 15:16:51 +00002143PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 if (v == NULL || !PyList_Check(v)) {
2146 PyErr_BadInternalCall();
2147 return -1;
2148 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002149 v = list_sort_impl((PyListObject *)v, NULL, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002150 if (v == NULL)
2151 return -1;
2152 Py_DECREF(v);
2153 return 0;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002154}
2155
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002156/*[clinic input]
2157list.reverse
2158
2159Reverse *IN PLACE*.
2160[clinic start generated code]*/
2161
Guido van Rossumb86c5492001-02-12 22:06:02 +00002162static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002163list_reverse_impl(PyListObject *self)
2164/*[clinic end generated code: output=482544fc451abea9 input=eefd4c3ae1bc9887]*/
Guido van Rossumb86c5492001-02-12 22:06:02 +00002165{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 if (Py_SIZE(self) > 1)
2167 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
2168 Py_RETURN_NONE;
Guido van Rossumed98d481991-03-06 13:07:53 +00002169}
2170
Guido van Rossum84c76f51990-10-30 13:32:20 +00002171int
Fred Drakea2f55112000-07-09 15:16:51 +00002172PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002173{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 PyListObject *self = (PyListObject *)v;
Tim Peters6063e262002-08-08 01:06:39 +00002175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 if (v == NULL || !PyList_Check(v)) {
2177 PyErr_BadInternalCall();
2178 return -1;
2179 }
2180 if (Py_SIZE(self) > 1)
2181 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
2182 return 0;
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002183}
2184
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002185PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002186PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002187{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002188 PyObject *w;
2189 PyObject **p, **q;
2190 Py_ssize_t n;
2191 if (v == NULL || !PyList_Check(v)) {
2192 PyErr_BadInternalCall();
2193 return NULL;
2194 }
2195 n = Py_SIZE(v);
2196 w = PyTuple_New(n);
2197 if (w == NULL)
2198 return NULL;
2199 p = ((PyTupleObject *)w)->ob_item;
2200 q = ((PyListObject *)v)->ob_item;
2201 while (--n >= 0) {
2202 Py_INCREF(*q);
2203 *p = *q;
2204 p++;
2205 q++;
2206 }
2207 return w;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002208}
2209
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002210/*[clinic input]
2211list.index
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002212
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002213 value: object
Serhiy Storchaka80ec8362017-03-19 19:37:40 +02002214 start: slice_index(accept={int}) = 0
2215 stop: slice_index(accept={int}, c_default="PY_SSIZE_T_MAX") = sys.maxsize
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002216 /
2217
2218Return first index of value.
2219
2220Raises ValueError if the value is not present.
2221[clinic start generated code]*/
2222
2223static PyObject *
2224list_index_impl(PyListObject *self, PyObject *value, Py_ssize_t start,
2225 Py_ssize_t stop)
Serhiy Storchaka80ec8362017-03-19 19:37:40 +02002226/*[clinic end generated code: output=ec51b88787e4e481 input=40ec5826303a0eb1]*/
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002227{
2228 Py_ssize_t i;
2229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 if (start < 0) {
2231 start += Py_SIZE(self);
2232 if (start < 0)
2233 start = 0;
2234 }
2235 if (stop < 0) {
2236 stop += Py_SIZE(self);
2237 if (stop < 0)
2238 stop = 0;
2239 }
2240 for (i = start; i < stop && i < Py_SIZE(self); i++) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002241 int cmp = PyObject_RichCompareBool(self->ob_item[i], value, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 if (cmp > 0)
2243 return PyLong_FromSsize_t(i);
2244 else if (cmp < 0)
2245 return NULL;
2246 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002247 PyErr_Format(PyExc_ValueError, "%R is not in list", value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002249}
2250
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002251/*[clinic input]
2252list.count
2253
2254 value: object
2255 /
2256
2257Return number of occurrences of value.
2258[clinic start generated code]*/
2259
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002260static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002261list_count(PyListObject *self, PyObject *value)
2262/*[clinic end generated code: output=b1f5d284205ae714 input=3bdc3a5e6f749565]*/
Guido van Rossume6f7d181991-10-20 20:20:40 +00002263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 Py_ssize_t count = 0;
2265 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002267 for (i = 0; i < Py_SIZE(self); i++) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002268 int cmp = PyObject_RichCompareBool(self->ob_item[i], value, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 if (cmp > 0)
2270 count++;
2271 else if (cmp < 0)
2272 return NULL;
2273 }
2274 return PyLong_FromSsize_t(count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002275}
2276
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002277/*[clinic input]
2278list.remove
2279
2280 value: object
2281 /
2282
2283Remove first occurrence of value.
2284
2285Raises ValueError if the value is not present.
2286[clinic start generated code]*/
2287
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002288static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002289list_remove(PyListObject *self, PyObject *value)
2290/*[clinic end generated code: output=f087e1951a5e30d1 input=2dc2ba5bb2fb1f82]*/
Guido van Rossumed98d481991-03-06 13:07:53 +00002291{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 for (i = 0; i < Py_SIZE(self); i++) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002295 int cmp = PyObject_RichCompareBool(self->ob_item[i], value, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 if (cmp > 0) {
2297 if (list_ass_slice(self, i, i+1,
2298 (PyObject *)NULL) == 0)
2299 Py_RETURN_NONE;
2300 return NULL;
2301 }
2302 else if (cmp < 0)
2303 return NULL;
2304 }
2305 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
2306 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002307}
2308
Jeremy Hylton8caad492000-06-23 14:18:11 +00002309static int
2310list_traverse(PyListObject *o, visitproc visit, void *arg)
2311{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002312 Py_ssize_t i;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002314 for (i = Py_SIZE(o); --i >= 0; )
2315 Py_VISIT(o->ob_item[i]);
2316 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002317}
2318
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002319static PyObject *
2320list_richcompare(PyObject *v, PyObject *w, int op)
2321{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002322 PyListObject *vl, *wl;
2323 Py_ssize_t i;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002324
Brian Curtindfc80e32011-08-10 20:28:54 -05002325 if (!PyList_Check(v) || !PyList_Check(w))
2326 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 vl = (PyListObject *)v;
2329 wl = (PyListObject *)w;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) {
2332 /* Shortcut: if the lengths differ, the lists differ */
2333 PyObject *res;
2334 if (op == Py_EQ)
2335 res = Py_False;
2336 else
2337 res = Py_True;
2338 Py_INCREF(res);
2339 return res;
2340 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002342 /* Search for the first index where items are different */
2343 for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) {
2344 int k = PyObject_RichCompareBool(vl->ob_item[i],
2345 wl->ob_item[i], Py_EQ);
2346 if (k < 0)
2347 return NULL;
2348 if (!k)
2349 break;
2350 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) {
2353 /* No more items to compare -- compare sizes */
2354 Py_ssize_t vs = Py_SIZE(vl);
2355 Py_ssize_t ws = Py_SIZE(wl);
2356 int cmp;
2357 PyObject *res;
2358 switch (op) {
2359 case Py_LT: cmp = vs < ws; break;
2360 case Py_LE: cmp = vs <= ws; break;
2361 case Py_EQ: cmp = vs == ws; break;
2362 case Py_NE: cmp = vs != ws; break;
2363 case Py_GT: cmp = vs > ws; break;
2364 case Py_GE: cmp = vs >= ws; break;
2365 default: return NULL; /* cannot happen */
2366 }
2367 if (cmp)
2368 res = Py_True;
2369 else
2370 res = Py_False;
2371 Py_INCREF(res);
2372 return res;
2373 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 /* We have an item that differs -- shortcuts for EQ/NE */
2376 if (op == Py_EQ) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02002377 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 }
2379 if (op == Py_NE) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02002380 Py_RETURN_TRUE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 /* Compare the final item again using the proper operator */
2384 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002385}
2386
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002387/*[clinic input]
2388list.__init__
2389
2390 iterable: object(c_default="NULL") = ()
2391 /
2392
2393Built-in mutable sequence.
2394
2395If no argument is given, the constructor creates a new empty list.
2396The argument must be an iterable if specified.
2397[clinic start generated code]*/
2398
Tim Peters6d6c1a32001-08-02 04:15:00 +00002399static int
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002400list___init___impl(PyListObject *self, PyObject *iterable)
2401/*[clinic end generated code: output=0f3c21379d01de48 input=b3f3fe7206af8f6b]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +00002402{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002403 /* Verify list invariants established by PyType_GenericAlloc() */
2404 assert(0 <= Py_SIZE(self));
2405 assert(Py_SIZE(self) <= self->allocated || self->allocated == -1);
2406 assert(self->ob_item != NULL ||
2407 self->allocated == 0 || self->allocated == -1);
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 /* Empty previous contents */
2410 if (self->ob_item != NULL) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002411 (void)_list_clear(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002412 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002413 if (iterable != NULL) {
2414 PyObject *rv = list_extend(self, iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 if (rv == NULL)
2416 return -1;
2417 Py_DECREF(rv);
2418 }
2419 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002420}
2421
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002422/*[clinic input]
2423list.__sizeof__
2424
2425Return the size of the list in memory, in bytes.
2426[clinic start generated code]*/
2427
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002428static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002429list___sizeof___impl(PyListObject *self)
2430/*[clinic end generated code: output=3417541f95f9a53e input=b8030a5d5ce8a187]*/
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002431{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002432 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002433
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02002434 res = _PyObject_SIZE(Py_TYPE(self)) + self->allocated * sizeof(void*);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002435 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002436}
2437
Raymond Hettinger1021c442003-11-07 15:38:09 +00002438static PyObject *list_iter(PyObject *seq);
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002439static PyObject *list_subscript(PyListObject*, PyObject*);
2440
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002441static PyMethodDef list_methods[] = {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002442 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, "x.__getitem__(y) <==> x[y]"},
2443 LIST___REVERSED___METHODDEF
2444 LIST___SIZEOF___METHODDEF
2445 LIST_CLEAR_METHODDEF
2446 LIST_COPY_METHODDEF
2447 LIST_APPEND_METHODDEF
2448 LIST_INSERT_METHODDEF
2449 LIST_EXTEND_METHODDEF
2450 LIST_POP_METHODDEF
2451 LIST_REMOVE_METHODDEF
2452 LIST_INDEX_METHODDEF
2453 LIST_COUNT_METHODDEF
2454 LIST_REVERSE_METHODDEF
2455 LIST_SORT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002456 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002457};
2458
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002459static PySequenceMethods list_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002460 (lenfunc)list_length, /* sq_length */
2461 (binaryfunc)list_concat, /* sq_concat */
2462 (ssizeargfunc)list_repeat, /* sq_repeat */
2463 (ssizeargfunc)list_item, /* sq_item */
2464 0, /* sq_slice */
2465 (ssizeobjargproc)list_ass_item, /* sq_ass_item */
2466 0, /* sq_ass_slice */
2467 (objobjproc)list_contains, /* sq_contains */
2468 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
2469 (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002470};
2471
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002472static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002473list_subscript(PyListObject* self, PyObject* item)
2474{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002475 if (PyIndex_Check(item)) {
2476 Py_ssize_t i;
2477 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2478 if (i == -1 && PyErr_Occurred())
2479 return NULL;
2480 if (i < 0)
2481 i += PyList_GET_SIZE(self);
2482 return list_item(self, i);
2483 }
2484 else if (PySlice_Check(item)) {
2485 Py_ssize_t start, stop, step, slicelength, cur, i;
2486 PyObject* result;
2487 PyObject* it;
2488 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002489
Serhiy Storchakab879fe82017-04-08 09:53:51 +03002490 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002491 return NULL;
2492 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +03002493 slicelength = PySlice_AdjustIndices(Py_SIZE(self), &start, &stop,
2494 step);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002496 if (slicelength <= 0) {
2497 return PyList_New(0);
2498 }
2499 else if (step == 1) {
2500 return list_slice(self, start, stop);
2501 }
2502 else {
2503 result = PyList_New(slicelength);
2504 if (!result) return NULL;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002506 src = self->ob_item;
2507 dest = ((PyListObject *)result)->ob_item;
2508 for (cur = start, i = 0; i < slicelength;
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002509 cur += (size_t)step, i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002510 it = src[cur];
2511 Py_INCREF(it);
2512 dest[i] = it;
2513 }
Tim Peters3b01a122002-07-19 02:35:45 +00002514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002515 return result;
2516 }
2517 }
2518 else {
2519 PyErr_Format(PyExc_TypeError,
Terry Jan Reedyffff1442014-08-02 01:30:37 -04002520 "list indices must be integers or slices, not %.200s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002521 item->ob_type->tp_name);
2522 return NULL;
2523 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002524}
2525
Tim Peters3b01a122002-07-19 02:35:45 +00002526static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002527list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2528{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002529 if (PyIndex_Check(item)) {
2530 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2531 if (i == -1 && PyErr_Occurred())
2532 return -1;
2533 if (i < 0)
2534 i += PyList_GET_SIZE(self);
2535 return list_ass_item(self, i, value);
2536 }
2537 else if (PySlice_Check(item)) {
2538 Py_ssize_t start, stop, step, slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002539
Serhiy Storchakab879fe82017-04-08 09:53:51 +03002540 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 return -1;
2542 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +03002543 slicelength = PySlice_AdjustIndices(Py_SIZE(self), &start, &stop,
2544 step);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002546 if (step == 1)
2547 return list_ass_slice(self, start, stop, value);
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002549 /* Make sure s[5:2] = [..] inserts at the right place:
2550 before 5, not before 2. */
2551 if ((step < 0 && start < stop) ||
2552 (step > 0 && start > stop))
2553 stop = start;
Thomas Woutersed03b412007-08-28 21:37:11 +00002554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002555 if (value == NULL) {
2556 /* delete slice */
2557 PyObject **garbage;
2558 size_t cur;
2559 Py_ssize_t i;
Victor Stinner35f28032013-11-21 12:16:35 +01002560 int res;
Tim Peters3b01a122002-07-19 02:35:45 +00002561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 if (slicelength <= 0)
2563 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002565 if (step < 0) {
2566 stop = start + 1;
2567 start = stop + step*(slicelength - 1) - 1;
2568 step = -step;
2569 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002571 garbage = (PyObject**)
2572 PyMem_MALLOC(slicelength*sizeof(PyObject*));
2573 if (!garbage) {
2574 PyErr_NoMemory();
2575 return -1;
2576 }
Tim Peters3b01a122002-07-19 02:35:45 +00002577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002578 /* drawing pictures might help understand these for
2579 loops. Basically, we memmove the parts of the
2580 list that are *not* part of the slice: step-1
2581 items for each item that is part of the slice,
2582 and then tail end of the list that was not
2583 covered by the slice */
2584 for (cur = start, i = 0;
2585 cur < (size_t)stop;
2586 cur += step, i++) {
2587 Py_ssize_t lim = step - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002589 garbage[i] = PyList_GET_ITEM(self, cur);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002591 if (cur + step >= (size_t)Py_SIZE(self)) {
2592 lim = Py_SIZE(self) - cur - 1;
2593 }
Michael W. Hudson56796f62002-07-29 14:35:04 +00002594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002595 memmove(self->ob_item + cur - i,
2596 self->ob_item + cur + 1,
2597 lim * sizeof(PyObject *));
2598 }
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002599 cur = start + (size_t)slicelength * step;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002600 if (cur < (size_t)Py_SIZE(self)) {
2601 memmove(self->ob_item + cur - slicelength,
2602 self->ob_item + cur,
2603 (Py_SIZE(self) - cur) *
2604 sizeof(PyObject *));
2605 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002607 Py_SIZE(self) -= slicelength;
Victor Stinner35f28032013-11-21 12:16:35 +01002608 res = list_resize(self, Py_SIZE(self));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002610 for (i = 0; i < slicelength; i++) {
2611 Py_DECREF(garbage[i]);
2612 }
2613 PyMem_FREE(garbage);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002614
Victor Stinner35f28032013-11-21 12:16:35 +01002615 return res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002616 }
2617 else {
2618 /* assign slice */
2619 PyObject *ins, *seq;
2620 PyObject **garbage, **seqitems, **selfitems;
2621 Py_ssize_t cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002623 /* protect against a[::-1] = a */
2624 if (self == (PyListObject*)value) {
2625 seq = list_slice((PyListObject*)value, 0,
2626 PyList_GET_SIZE(value));
2627 }
2628 else {
2629 seq = PySequence_Fast(value,
2630 "must assign iterable "
2631 "to extended slice");
2632 }
2633 if (!seq)
2634 return -1;
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002636 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2637 PyErr_Format(PyExc_ValueError,
2638 "attempt to assign sequence of "
2639 "size %zd to extended slice of "
2640 "size %zd",
2641 PySequence_Fast_GET_SIZE(seq),
2642 slicelength);
2643 Py_DECREF(seq);
2644 return -1;
2645 }
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002647 if (!slicelength) {
2648 Py_DECREF(seq);
2649 return 0;
2650 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 garbage = (PyObject**)
2653 PyMem_MALLOC(slicelength*sizeof(PyObject*));
2654 if (!garbage) {
2655 Py_DECREF(seq);
2656 PyErr_NoMemory();
2657 return -1;
2658 }
Tim Peters3b01a122002-07-19 02:35:45 +00002659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002660 selfitems = self->ob_item;
2661 seqitems = PySequence_Fast_ITEMS(seq);
2662 for (cur = start, i = 0; i < slicelength;
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002663 cur += (size_t)step, i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002664 garbage[i] = selfitems[cur];
2665 ins = seqitems[i];
2666 Py_INCREF(ins);
2667 selfitems[cur] = ins;
2668 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002670 for (i = 0; i < slicelength; i++) {
2671 Py_DECREF(garbage[i]);
2672 }
Tim Peters3b01a122002-07-19 02:35:45 +00002673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002674 PyMem_FREE(garbage);
2675 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002677 return 0;
2678 }
2679 }
2680 else {
2681 PyErr_Format(PyExc_TypeError,
Terry Jan Reedyffff1442014-08-02 01:30:37 -04002682 "list indices must be integers or slices, not %.200s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002683 item->ob_type->tp_name);
2684 return -1;
2685 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002686}
2687
2688static PyMappingMethods list_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002689 (lenfunc)list_length,
2690 (binaryfunc)list_subscript,
2691 (objobjargproc)list_ass_subscript
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002692};
2693
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002694PyTypeObject PyList_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002695 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2696 "list",
2697 sizeof(PyListObject),
2698 0,
2699 (destructor)list_dealloc, /* tp_dealloc */
2700 0, /* tp_print */
2701 0, /* tp_getattr */
2702 0, /* tp_setattr */
2703 0, /* tp_reserved */
2704 (reprfunc)list_repr, /* tp_repr */
2705 0, /* tp_as_number */
2706 &list_as_sequence, /* tp_as_sequence */
2707 &list_as_mapping, /* tp_as_mapping */
Georg Brandl00da4e02010-10-18 07:32:48 +00002708 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002709 0, /* tp_call */
2710 0, /* tp_str */
2711 PyObject_GenericGetAttr, /* tp_getattro */
2712 0, /* tp_setattro */
2713 0, /* tp_as_buffer */
2714 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002715 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */
2716 list___init____doc__, /* tp_doc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002717 (traverseproc)list_traverse, /* tp_traverse */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002718 (inquiry)_list_clear, /* tp_clear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002719 list_richcompare, /* tp_richcompare */
2720 0, /* tp_weaklistoffset */
2721 list_iter, /* tp_iter */
2722 0, /* tp_iternext */
2723 list_methods, /* tp_methods */
2724 0, /* tp_members */
2725 0, /* tp_getset */
2726 0, /* tp_base */
2727 0, /* tp_dict */
2728 0, /* tp_descr_get */
2729 0, /* tp_descr_set */
2730 0, /* tp_dictoffset */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002731 (initproc)list___init__, /* tp_init */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002732 PyType_GenericAlloc, /* tp_alloc */
2733 PyType_GenericNew, /* tp_new */
2734 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002735};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002736
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002737/*********************** List Iterator **************************/
2738
2739typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002740 PyObject_HEAD
Victor Stinner7660b882013-06-24 23:59:24 +02002741 Py_ssize_t it_index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002742 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002743} listiterobject;
2744
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002745static void listiter_dealloc(listiterobject *);
2746static int listiter_traverse(listiterobject *, visitproc, void *);
2747static PyObject *listiter_next(listiterobject *);
2748static PyObject *listiter_len(listiterobject *);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002749static PyObject *listiter_reduce_general(void *_it, int forward);
2750static PyObject *listiter_reduce(listiterobject *);
2751static PyObject *listiter_setstate(listiterobject *, PyObject *state);
Raymond Hettinger435bf582004-03-18 22:43:10 +00002752
Armin Rigof5b3e362006-02-11 21:32:43 +00002753PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002754PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
2755PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002756
2757static PyMethodDef listiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002758 {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002759 {"__reduce__", (PyCFunction)listiter_reduce, METH_NOARGS, reduce_doc},
2760 {"__setstate__", (PyCFunction)listiter_setstate, METH_O, setstate_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002761 {NULL, NULL} /* sentinel */
Raymond Hettinger435bf582004-03-18 22:43:10 +00002762};
2763
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002764PyTypeObject PyListIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002765 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2766 "list_iterator", /* tp_name */
2767 sizeof(listiterobject), /* tp_basicsize */
2768 0, /* tp_itemsize */
2769 /* methods */
2770 (destructor)listiter_dealloc, /* tp_dealloc */
2771 0, /* tp_print */
2772 0, /* tp_getattr */
2773 0, /* tp_setattr */
2774 0, /* tp_reserved */
2775 0, /* tp_repr */
2776 0, /* tp_as_number */
2777 0, /* tp_as_sequence */
2778 0, /* tp_as_mapping */
2779 0, /* tp_hash */
2780 0, /* tp_call */
2781 0, /* tp_str */
2782 PyObject_GenericGetAttr, /* tp_getattro */
2783 0, /* tp_setattro */
2784 0, /* tp_as_buffer */
2785 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2786 0, /* tp_doc */
2787 (traverseproc)listiter_traverse, /* tp_traverse */
2788 0, /* tp_clear */
2789 0, /* tp_richcompare */
2790 0, /* tp_weaklistoffset */
2791 PyObject_SelfIter, /* tp_iter */
2792 (iternextfunc)listiter_next, /* tp_iternext */
2793 listiter_methods, /* tp_methods */
2794 0, /* tp_members */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002795};
Raymond Hettinger1021c442003-11-07 15:38:09 +00002796
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002797
2798static PyObject *
2799list_iter(PyObject *seq)
2800{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002801 listiterobject *it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002803 if (!PyList_Check(seq)) {
2804 PyErr_BadInternalCall();
2805 return NULL;
2806 }
2807 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2808 if (it == NULL)
2809 return NULL;
2810 it->it_index = 0;
2811 Py_INCREF(seq);
2812 it->it_seq = (PyListObject *)seq;
2813 _PyObject_GC_TRACK(it);
2814 return (PyObject *)it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002815}
2816
2817static void
2818listiter_dealloc(listiterobject *it)
2819{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002820 _PyObject_GC_UNTRACK(it);
2821 Py_XDECREF(it->it_seq);
2822 PyObject_GC_Del(it);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002823}
2824
2825static int
2826listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2827{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002828 Py_VISIT(it->it_seq);
2829 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002830}
2831
2832static PyObject *
2833listiter_next(listiterobject *it)
2834{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002835 PyListObject *seq;
2836 PyObject *item;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002838 assert(it != NULL);
2839 seq = it->it_seq;
2840 if (seq == NULL)
2841 return NULL;
2842 assert(PyList_Check(seq));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002844 if (it->it_index < PyList_GET_SIZE(seq)) {
2845 item = PyList_GET_ITEM(seq, it->it_index);
2846 ++it->it_index;
2847 Py_INCREF(item);
2848 return item;
2849 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002851 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03002852 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002853 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002854}
2855
2856static PyObject *
2857listiter_len(listiterobject *it)
2858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002859 Py_ssize_t len;
2860 if (it->it_seq) {
2861 len = PyList_GET_SIZE(it->it_seq) - it->it_index;
2862 if (len >= 0)
2863 return PyLong_FromSsize_t(len);
2864 }
2865 return PyLong_FromLong(0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002866}
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002867
2868static PyObject *
2869listiter_reduce(listiterobject *it)
2870{
2871 return listiter_reduce_general(it, 1);
2872}
2873
2874static PyObject *
2875listiter_setstate(listiterobject *it, PyObject *state)
2876{
Victor Stinner7660b882013-06-24 23:59:24 +02002877 Py_ssize_t index = PyLong_AsSsize_t(state);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002878 if (index == -1 && PyErr_Occurred())
2879 return NULL;
2880 if (it->it_seq != NULL) {
2881 if (index < 0)
2882 index = 0;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +00002883 else if (index > PyList_GET_SIZE(it->it_seq))
2884 index = PyList_GET_SIZE(it->it_seq); /* iterator exhausted */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002885 it->it_index = index;
2886 }
2887 Py_RETURN_NONE;
2888}
2889
Raymond Hettinger1021c442003-11-07 15:38:09 +00002890/*********************** List Reverse Iterator **************************/
2891
2892typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002893 PyObject_HEAD
2894 Py_ssize_t it_index;
2895 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002896} listreviterobject;
2897
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002898static void listreviter_dealloc(listreviterobject *);
2899static int listreviter_traverse(listreviterobject *, visitproc, void *);
2900static PyObject *listreviter_next(listreviterobject *);
Raymond Hettingerf5b64112008-12-02 21:33:45 +00002901static PyObject *listreviter_len(listreviterobject *);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002902static PyObject *listreviter_reduce(listreviterobject *);
2903static PyObject *listreviter_setstate(listreviterobject *, PyObject *);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002904
Raymond Hettingerf5b64112008-12-02 21:33:45 +00002905static PyMethodDef listreviter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002906 {"__length_hint__", (PyCFunction)listreviter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002907 {"__reduce__", (PyCFunction)listreviter_reduce, METH_NOARGS, reduce_doc},
2908 {"__setstate__", (PyCFunction)listreviter_setstate, METH_O, setstate_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002909 {NULL, NULL} /* sentinel */
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002910};
2911
Raymond Hettinger1021c442003-11-07 15:38:09 +00002912PyTypeObject PyListRevIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002913 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2914 "list_reverseiterator", /* tp_name */
2915 sizeof(listreviterobject), /* tp_basicsize */
2916 0, /* tp_itemsize */
2917 /* methods */
2918 (destructor)listreviter_dealloc, /* tp_dealloc */
2919 0, /* tp_print */
2920 0, /* tp_getattr */
2921 0, /* tp_setattr */
2922 0, /* tp_reserved */
2923 0, /* tp_repr */
2924 0, /* tp_as_number */
2925 0, /* tp_as_sequence */
2926 0, /* tp_as_mapping */
2927 0, /* tp_hash */
2928 0, /* tp_call */
2929 0, /* tp_str */
2930 PyObject_GenericGetAttr, /* tp_getattro */
2931 0, /* tp_setattro */
2932 0, /* tp_as_buffer */
2933 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2934 0, /* tp_doc */
2935 (traverseproc)listreviter_traverse, /* tp_traverse */
2936 0, /* tp_clear */
2937 0, /* tp_richcompare */
2938 0, /* tp_weaklistoffset */
2939 PyObject_SelfIter, /* tp_iter */
2940 (iternextfunc)listreviter_next, /* tp_iternext */
2941 listreviter_methods, /* tp_methods */
2942 0,
Raymond Hettinger1021c442003-11-07 15:38:09 +00002943};
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002944
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002945/*[clinic input]
2946list.__reversed__
2947
2948Return a reverse iterator over the list.
2949[clinic start generated code]*/
2950
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002951static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002952list___reversed___impl(PyListObject *self)
2953/*[clinic end generated code: output=b166f073208c888c input=eadb6e17f8a6a280]*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002954{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002955 listreviterobject *it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002957 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
2958 if (it == NULL)
2959 return NULL;
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002960 assert(PyList_Check(self));
2961 it->it_index = PyList_GET_SIZE(self) - 1;
2962 Py_INCREF(self);
2963 it->it_seq = self;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002964 PyObject_GC_Track(it);
2965 return (PyObject *)it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002966}
2967
2968static void
2969listreviter_dealloc(listreviterobject *it)
2970{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002971 PyObject_GC_UnTrack(it);
2972 Py_XDECREF(it->it_seq);
2973 PyObject_GC_Del(it);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002974}
2975
2976static int
2977listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
2978{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002979 Py_VISIT(it->it_seq);
2980 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002981}
2982
2983static PyObject *
2984listreviter_next(listreviterobject *it)
2985{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002986 PyObject *item;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03002987 Py_ssize_t index;
2988 PyListObject *seq;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002989
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03002990 assert(it != NULL);
2991 seq = it->it_seq;
2992 if (seq == NULL) {
2993 return NULL;
2994 }
2995 assert(PyList_Check(seq));
2996
2997 index = it->it_index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002998 if (index>=0 && index < PyList_GET_SIZE(seq)) {
2999 item = PyList_GET_ITEM(seq, index);
3000 it->it_index--;
3001 Py_INCREF(item);
3002 return item;
3003 }
3004 it->it_index = -1;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003005 it->it_seq = NULL;
3006 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003007 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003008}
3009
Raymond Hettingerf5b64112008-12-02 21:33:45 +00003010static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003011listreviter_len(listreviterobject *it)
3012{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003013 Py_ssize_t len = it->it_index + 1;
3014 if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
3015 len = 0;
3016 return PyLong_FromSsize_t(len);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003017}
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003018
3019static PyObject *
3020listreviter_reduce(listreviterobject *it)
3021{
3022 return listiter_reduce_general(it, 0);
3023}
3024
3025static PyObject *
3026listreviter_setstate(listreviterobject *it, PyObject *state)
3027{
3028 Py_ssize_t index = PyLong_AsSsize_t(state);
3029 if (index == -1 && PyErr_Occurred())
3030 return NULL;
3031 if (it->it_seq != NULL) {
3032 if (index < -1)
3033 index = -1;
3034 else if (index > PyList_GET_SIZE(it->it_seq) - 1)
3035 index = PyList_GET_SIZE(it->it_seq) - 1;
3036 it->it_index = index;
3037 }
3038 Py_RETURN_NONE;
3039}
3040
3041/* common pickling support */
3042
3043static PyObject *
3044listiter_reduce_general(void *_it, int forward)
3045{
3046 PyObject *list;
3047
3048 /* the objects are not the same, index is of different types! */
3049 if (forward) {
3050 listiterobject *it = (listiterobject *)_it;
3051 if (it->it_seq)
Victor Stinner7660b882013-06-24 23:59:24 +02003052 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003053 it->it_seq, it->it_index);
3054 } else {
3055 listreviterobject *it = (listreviterobject *)_it;
3056 if (it->it_seq)
Antoine Pitroua7013882012-04-05 00:04:20 +02003057 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("reversed"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003058 it->it_seq, it->it_index);
3059 }
3060 /* empty iterator, create an empty list */
3061 list = PyList_New(0);
3062 if (list == NULL)
3063 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +02003064 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), list);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003065}